Link to home
Start Free TrialLog in
Avatar of Wanda Marston
Wanda MarstonFlag for Canada

asked on

Can someone tell me how to integrate a specific snippet of html code into a piece of PHP code?

I am trying to integrate code into a php document that will show / hide a password. The following code was previously supplied by an expert on Experts Exchange. 

Open in new window

  <div class="toggle-button">
    <input type="password" name="password">     <button         type="button"         onmousedown="this.form.password.type='text'"         onmouseup="this.form.password.type='password'">     </button>   </div>

Open in new window

The PHP code I am trying to meld this code with is as follows;

<p><label for="pass2" class="SmallHeading"><strong>Password</strong></label></p>
<?php create_form_input ('pass', 'password',  $login_errors);  ?> <button class="button" style="vertical-align:left"><span>Login &rarr;</span></button> </form>

Open in new window

Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Hi Wanda,

If the show/hide is supposed to work based on a mouse click or other interaction with the browser, that should be done by javascript.

If you are just trying to render that code from your php, then use heredoc
https://www.php.net/manual/en/language.types.string.php

$form = <<< END
 <div class="toggle-button">
    <input type="password" name="password">
    <button
       type="button"
       onmousedown="this.form.password.type='text'"
       onmouseup="this.form.password.type='password'">
    </button>
  </div>
END; 


echo $form;

Open in new window


For your log in errors $login_errors


$login_errors = '<div class="error">This is the error</div>';




 $form = <<< END
 <div class="toggle-button">
    <input type="password" name="password">
    <button
       type="button"
       onmousedown="this.form.password.type='text'"
       onmouseup="this.form.password.type='password'">
    </button>
   $login_errors  
  </div>
END;




echo $form;

Open in new window


Hey Wanda,

We don't know what your create_form_input function is creating in terms of the HTML, so I can't give you a specific answer, but that snippet of HTML you've provided should just be added directly to your PHP code.

The toggling of visibility is done by changing the type from password to text and back again, so the JS you have in the onmousedown / onmouseup buttons needs to reference the correct name - you may need to change the name of the password field as I'm guessing your create_form_input creates an input named 'pass')

<p><label for="pass" class="SmallHeading"><strong>Password</strong></label></p>
<?php create_form_input ('pass', 'password',  $login_errors);  ?>
<button type="button" 
    onmousedown="this.form.pass.type='text'" 
    onmouseup="this.form.pass.type='password'">
</button>
<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>

Open in new window

Avatar of Wanda Marston

ASKER

Following is my forms function file.

<?php


// Defines any functions required by the various forms for the YARN EXTRAS Site.


// This function generates a form INPUT or TEXTAREA tag.
// It takes three arguments:
// - The name to be given to the element.
// - The type of element (text, password, textarea).
// - An array of errors.


function create_form_input($name, $type, $errors) {
   
    // Assume no value already exists:
    $value = false;


    // Check for a value in POST:
    if (isset($_POST[$name])) $value = $_POST[$name];
   
    // Strip slashes if Magic Quotes is enabled:
    if ($value && get_magic_quotes_gpc()) $value = stripslashes($value);


// Conditional to determine what kind of element to create
   
    if (($type == 'text') || ($type == 'password') || ($type == 'checkbox')) { // Create text or password inputs.
       
        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" id="myInput"' . $name . '" size=50"';
       
        // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';


        // Check for an error:
        if (array_key_exists($name, $errors)) {
            echo 'class="error" /> <span class="error">' . $errors[$name] . '</span>';
        } else {
            echo ' />';        
        }
           
       
    } elseif ($type == 'textarea') { // Create a TEXTAREA.
       
        // Display the error first:
        if (array_key_exists($name, $errors)) echo ' <span class="error">' . $errors[$name] . '</span>';


        // Start creating the textarea:
        echo '<textarea name="' . $name . '" id="' . $name . '" rows="5" cols="43"';
       
        // Add the error class, if applicable:
        if (array_key_exists($name, $errors)) {
            echo ' class="error">';
        } else {
            echo '>';        
        }
       
        // Add the value to the textarea:
        if ($value) echo $value;


        // Complete the textarea:
        echo '</textarea>';
       
} elseif ($type == 'checkbox') { // Create a CHECKBOX.


        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" value="';


       
       // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';
       
       
        // Display the error:
        if (array_key_exists($name, $errors)) {
           
            echo ' />';        
        }
    } // End of primary IF-ELSE.


}// End of the create_form_input() function.


// Omit the closing PHP tag to avoid 'headers already sent' errors!

Open in new window


I am getting closer with this code. I have two versions of the code on my "login_form.inc.php". They both SHOW the email address instead of the password. Following is the Javascript on the user's Login page.

<script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>

Open in new window

       
The following is the code on the login_form.inc.php

<?php

// This script displays the login form for YARN EXTRAS.
// Worked on September 20, 2021

// Create an empty error array if it doesn't already exist:
if (!isset($login_errors)) $login_errors = array();

// Need the form functions script, which defines create_form_input():
require_once ('./includes/form_functions.inc.php');
?>

<form action="Login.php" method="post" accept-charset="utf-8">

<h2>LOGIN</h2>
    
<?php if (array_key_exists('login', $login_errors)) {
echo '<span class="error">' . $login_errors['login'] . '</span>'; }?></p>

<label for="email" class="SmallHeading"><strong>Email Address</strong></label>
<?php create_form_input('email', 'text', $login_errors); ?></p>

<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>

<label for="pass2" class="SmallHeading" value="FakePSW" id="myInput"><strong>Password</strong></label>
<?php create_form_input ('pass', 'password',  $login_errors);  ?>
<input type="checkbox" onclick="myFunction()"> This is another version Show Password

<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>

Password: <input type="password" value="FakePSW" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password

Open in new window

Hey Wanda,

You seem to getting futher away from your solution. In the code you've just posted, you're now calling a function (myFunction) which tries to set the 'type' of an input with the ID of #myInput. In your code, that's your label, so it won't work:

<label for="pass2" class="SmallHeading" value="FakePSW" id="myInput">

Also, your create_form_input() function seems to add an ID of myInput to every element it creates. An ID needs to be unique within the page, so that's going to cause you problems as well.

All you need to do is add your button after you form field and you'll be good to go. Here's a quick working demo: https://jsfiddle.net/ChrisStanyon/7dtfh2s5/
I don't believe that any of the Experts can provide a solution all thing considered.

I do not want to change all of my previous code at the present time or start using other code applications such as jQuery and Codepen.

I just wanted to ADD to what I have. This is something I want to add on a site that is already live.



Wanda, there is no jquery that I can see that has been provided to you.

I am confused what the real issue is.  If your question has something to do with your javascript you posted,User generated imageThen php is not part of the issue and may be confusing things.

If you have an input like
<input id="myInput" type="password">

Open in new window

Then run the following
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}


myFunction();

Open in new window


I found it works as expected where it converts the input type "password" to text allowing you to view the input. But if you instead use the input
<input id="myInput" type="text">

Open in new window

then the code successfully changes the field to type password and changes the text to dots.

To help clarify what you are after, please render your form code into pure html. Then let us know what is happening when the form runs vs what is expected. All we have from your last comment is:

 "I am getting closer with this code. I have two versions of the code on my login_form.inc.php". They both SHOW the email address instead of the password. Following is the Javascript on the user's Login page"

Either something is wrong in the code, or there is a misunderstanding of what is supposed to happen when a form field is set to password vs text.
I think that the php that is on another page and part of the whole process is possibly the problem. I don't want to go backward and change all of that code. I was hoping when I first asked the question that it would be a more simple matter of adding the javascript within the Login page itself. I discovered something different as I started receiving suggestions.
Not all the time, but sometimes, it is actually physically easier to change to another method of doing things that will also make it easier later on. Mentally, it is a hard hurdle to get over. Be cognisant of that when taking suggestions.

What is missing here is a clear definition of the issue. It may very well be clear to you because you are experiencing it, but from our side, it is confusing as to what the real issue is.

Your question is stating, "I am trying to integrate code into a php document that will show / hide a password. The following code was previously supplied by an expert on Experts Exchange."

Typically, show/hide of a password means this is a client-side function, so no PHP is involved. The only code we need is your rendered HTML code.

What you are showing us is the PHP that is probably just calling another function somewhere that will render the HTML for the form.
<?php create_form_input ('pass', 'password',  $login_errors);  ?>

Open in new window

You just need to run the page, view the source and copy and paste just the HTML from the start to close  <form> .... ...</form> tag.  Simply just giving us your back end code like this https://www.experts-exchange.com/questions/29224783/Can-someone-tell-me-how-to-integrate-a-specific-snippet-of-html-code-into-a-piece-of-PHP-code.html#a43341966  does not help us. We need to see the rendered html.

From there, showing and hiding the password is going to be a javascript function. Chris has given you one option here https://www.experts-exchange.com/questions/29224783/Can-someone-tell-me-how-to-integrate-a-specific-snippet-of-html-code-into-a-piece-of-PHP-code.html#a43342025 

For what you are talking about, I don't think there will be any reason to go back and adjust a lot of code, just this one bit that is showing and hiding the password. 
Okay if you really think that I will NOT need to move backward and adjust a lot of code, I will attempt to try to find what is the stumbling block on the page where one would normally add the javascript.
I have tried it several different ways, worked many hours on this, not just this past question but previous attempts from time to time. I will get back to you as soon as I can.

Attached is a copy of the Login Form as it appears on the web browser without any kind of coding for the "show / hide password" code. This is what I would like to preserve.
User generated image
We would need to see the rendered HTML code. But in very simple terms, lets use this.
https://dojo.telerik.com/UDijAYIb
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
</head>
<body>
<form>
  <input type="text" id="username" name="username">
  <input type="password" id="password" name="password">
     <button
       type="button"
       onmousedown="this.form.password.type='text'"
       onmouseup="this.form.password.type='password'">
       show/hide
    </button>
</form>
</body>
</html>

Open in new window

If you click the show/hide button, I think it does what you expect.

Your form looks a lot nicer because you have CSS applied to the HTML.


Now let's look at your other example.
https://dojo.telerik.com/iGoGOpUR
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
</head>
<body>




<form action="Login.php" method="post" accept-charset="utf-8">


<h2>LOGIN</h2>
   




<label for="email" class="SmallHeading"><strong>Email Address</strong></label>




<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>


<label for="pass2" class="SmallHeading" value="FakePSW" id="myInput"><strong>Password</strong></label>


<input type="checkbox" onclick="myFunction()"> This is another version Show Password


<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>


Password: <input type="password" value="FakePSW" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password
</body>
</html>

Open in new window

This is taken from your example here https://www.experts-exchange.com/questions/29224783/Can-someone-tell-me-how-to-integrate-a-specific-snippet-of-html-code-into-a-piece-of-PHP-code.html#a43341966 except I stripped out the PHP. Again, no CSS so it will not look pretty but work the same.

I didn't see this at first, but after playing with it, I see why the show/hide does not work. Notice you have two id's set to myInput. Though physically you can duplicate ID's, but doing so will cause your javascript to fail and also make your HTML non-compliant.
https://dojo.telerik.com/aBOxoSir
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
</head>
<body>




<form action="Login.php" method="post" accept-charset="utf-8">


<h2>LOGIN</h2>
   




<label for="email" class="SmallHeading"><strong>Email Address</strong></label>




<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>


<label for="pass2" class="SmallHeading" value="FakePSW" id="myInputLabel"><strong>Password</strong></label>


<input type="checkbox" onclick="myFunction()"> This is another version Show Password


<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>


Password: <input type="password" value="FakePSW" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password
</body>
</html>

Open in new window


Perhaps this was the actual issue you were talking about all along?
Yes, your last comment could be correct. This could be the issue. 

I fooled around with it and I get either this error - Fatal error:  Uncaught ArgumentCountError: Too few arguments to function create_form_input(), 2 passed in /hermes/bosnacweb04/bosnacweb04aj/b717/nf./public_html/xxxxxxxxx.com/includes/login_form.inc.php on line 25 and exactly 3 expected in /hermes/bosnacweb04/bosnacweb04aj/b717/nf./public_html/xxxxxxx.com/includes/form_functions.inc.php:11 Stack trace: #0 /hermes/bosnacweb04/bosnacweb04aj/b717/nf.txxxxxxxxxx/public_html/xxxxxx.com/includes/login_form.inc.php(25): create_form_input('password', Array) #1 /hermes/bosnacweb04/bosnacweb04aj/b717/nf.xxxxxxxxxxxx/public_html/xxxxxxxx.com/Login.php(63): require('/hermes/bosnacw...') #2 {main}  thrown in /hermes/bosnacweb04/bosnacweb04aj/b717/nf.xxxxxxxxxx/public_html/xxxxxxxxxx.com/includes/form_functions.inc.php on line 11

OR a login error message - "You forgot to enter your password".

Following is the form functions code -

function create_form_input($name, $type, $errors) {
    
    // Assume no value already exists:
    $value = false;

    // Check for a value in POST:
    if (isset($_POST[$name])) $value = $_POST[$name];
    
    // Strip slashes if Magic Quotes is enabled:
    if ($value && get_magic_quotes_gpc()) $value = stripslashes($value);

// Conditional to determine what kind of element to create
    
    if (($type == 'text') || ($type == 'password') || ($type == 'checkbox')) { // Create text or password inputs.
        
        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" id="myInput"' . $name . '" size=50"';
        
        // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';

        // Check for an error:
        if (array_key_exists($name, $errors)) {
            echo 'class="error" /> <span class="error">' . $errors[$name] . '</span>';
        } else {
            echo ' />';        
        }

Open in new window


You are talking about two different issues unless I am just confused which could be the case.

The show/hide password issue has nothing to do with your PHP code, it is all javascript. If you go back to my examples I just posted, you can see that part works.

The issue you are referring to has to do with your function is expecting three variables and you are only providing two.

This is your function
function create_form_input($name, $type, $errors)

Open in new window

It is expecting $name,$type and $errors.

More confusing is in your original question your function reads
create_form_input ('pass', 'password',  $login_errors);

Open in new window

That is only expecting one variable.

What is the purpose of the function create_form_input? Is it to remember what was just posted in case of an error to allow you to fill in the form fields with what was already posted? 
Yes, I understand that the show / hide password is all javacript and by itself it DOES work. The javascript DOES work. It shows / or hides the password. Every Javascript code I have tried has worked on its own.

My form without the javascript works fine. When the login is submitted the user will be taken to the next page with their membership information.

When I try to integrate this javascript into the form and php that is already there, the user is not sent to the next page. There are errors.

The form is a "sticky" form that will tell the user that they forgot to enter a password or email address.


We have the show/hide issue resolved then.  

Now you need to work on the error which is telling you you do not have enough parameters being passed to your function.

See these lines of code
<?php create_form_input('email', 'text', $login_errors); ?></p>

Open in new window

<?php create_form_input ('pass', 'password',  $login_errors);  ?>

Open in new window

They work as expected if I put all of this together in one page like
<script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
<?php






// Defines any functions required by the various forms for the YARN EXTRAS Site.




// This function generates a form INPUT or TEXTAREA tag.
// It takes three arguments:
// - The name to be given to the element.
// - The type of element (text, password, textarea).
// - An array of errors.




function create_form_input($name, $type, $errors) {
   
    // Assume no value already exists:
    $value = false;




    // Check for a value in POST:
    if (isset($_POST[$name])) $value = $_POST[$name];
   
    // Strip slashes if Magic Quotes is enabled:
    if ($value && get_magic_quotes_gpc()) $value = stripslashes($value);




// Conditional to determine what kind of element to create
   
    if (($type == 'text') || ($type == 'password') || ($type == 'checkbox')) { // Create text or password inputs.
       
        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" id="myInput"' . $name . '" size=50"';
       
        // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';




        // Check for an error:
        if (array_key_exists($name, $errors)) {
            echo 'class="error" /> <span class="error">' . $errors[$name] . '</span>';
        } else {
            echo ' />';        
        }
           
       
    } elseif ($type == 'textarea') { // Create a TEXTAREA.
       
        // Display the error first:
        if (array_key_exists($name, $errors)) echo ' <span class="error">' . $errors[$name] . '</span>';




        // Start creating the textarea:
        echo '<textarea name="' . $name . '" id="' . $name . '" rows="5" cols="43"';
       
        // Add the error class, if applicable:
        if (array_key_exists($name, $errors)) {
            echo ' class="error">';
        } else {
            echo '>';        
        }
       
        // Add the value to the textarea:
        if ($value) echo $value;




        // Complete the textarea:
        echo '</textarea>';
       
} elseif ($type == 'checkbox') { // Create a CHECKBOX.




        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" value="';




       
       // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';
       
       
        // Display the error:
        if (array_key_exists($name, $errors)) {
           
            echo ' />';        
        }
    } // End of primary IF-ELSE.




}// End of the create_form_input() function.


// This script displays the login form for YARN EXTRAS.
// Worked on September 20, 2021






// Create an empty error array if it doesn't already exist:
    if (!isset($login_errors)) $login_errors = array();
// Need the form functions script, which defines create_form_input():


?>


<form action="Login.php" method="post" accept-charset="utf-8">


<h2>LOGIN</h2>
<?php
    
 if (array_key_exists('login', $login_errors)) {
echo '<span class="error">' . $login_errors['login'] . '</span>'; }?></p>


<label for="email" class="SmallHeading"><strong>Email Address</strong></label>
<?php create_form_input('email', 'text', $login_errors); ?></p>


<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>


<label for="pass2" class="SmallHeading" value="FakePSW" id="myInputLabel"><strong>Password</strong></label>
<?php create_form_input ('pass', 'password',  $login_errors);  ?>
<input type="checkbox" onclick="myFunction()"> This is another version Show Password


<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>


Password: <input type="password" value="FakePSW" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password

Open in new window


If I change
<?php create_form_input('email', 'text', $login_errors); ?></p>

Open in new window


to
<?php create_form_input( 'text', $login_errors); ?></p>

Open in new window

or
<?php create_form_input('email',  $login_errors); ?></p>

Open in new window

or
<?php create_form_input('email', 'text'); ?></p>

Open in new window

I generate a similar error that you are getting.  This means the code you actually have on your page may not be what  you are showing us.   Double check that for those two lines of code you are in fact passing three variables and that should be your solution.

The show / hide password javascript always worked by itself. My initial question was how to integrate the code into my PHP code, so there was never an issue with the javascipt code.

I have posted my rendered HTML code which contains the PHP code and no javascript as it was before I attempted to add any Javascript.

I do not want to go backward and change much of the php code on the includes files as it may interfere with coding on other pages.

SO the following is the HTML and / or PHP coding that could affect submitting the form and moving the user to the next page.

login.inc.php

<?php 

// Array for recording errors:
$login_errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}

// Validate the email address:
    if (!empty($_POST['email'])) {
        $e = mysqli_real_escape_string($db, $_POST['email']);
    } else {
        $e = FALSE;
        echo '<p class="error">You forgot to enter your email address!</p>';
    }
    // Validate the password:
    if (!empty($_POST['pass'])) {
        $p = trim($_POST['pass']);
    } else {
        $p = FALSE;
        echo '<p class="error">You forgot to enter your password!</p>';
    }
    if ($e && $p) { // If everything's OK.
        // Query the database:
        $q = "SELECT id, username, pass FROM users WHERE email='$e' AND active IS NULL";
        
        $r = mysqli_query($db, $q) or trigger_error("Query: $q\n<br>MySQLI_Error: " . mysqli_error($db));
        
if (@mysqli_num_rows($r) == 1) { // A match was made.
            
    // Fetch the values:
list($id, $username, $pass) = mysqli_fetch_array($r, MYSQLI_NUM);
            mysqli_free_result($r);
            
            // Check the password:
            if (password_verify($p, $pass)) {
                // Store the info in the session:
                // Store the data in a session:
    
    $_SESSION['user_id'] = $id;
    $_SESSION['username'] = $username;

                mysqli_close($db);
                
                // Redirect the user:
                //$url = BASE_URL . 'Login.php'; // Define the URL.
                
                //ob_end_clean(); // Delete the buffer.
                //header("Location: $url");
                
                header('Location: MemberProfileYE.php');
                exit(); // Quit the script.
            
            } else {
                echo '<p class="error">The email address and password entered do not match those on file. Have you deactivated your account?</p>';
            }
        } else { // No match was made.
            echo '<p class="error">Yarn Extras cannot find that email or password. Have not registered with Yarn Extras? Have you checked your  email for the activation link? </p>';
        }
    } else { // If everything wasn't OK.
        echo '<p class="error">Please try again.</p>';
    }
    mysqli_close($db);

// Omit the closing PHP tag to avoid 'headers already sent' errors!

Open in new window


login.form.php

<?php

// Create an empty error array if it doesn't already exist:
if (!isset($login_errors)) $login_errors = array();

// Need the form functions script, which defines create_form_input():
require_once ('./includes/form_functions.inc.php');
?>

<form action="Login.php" method="post" accept-charset="utf-8">

<h2>LOGIN</h2>
<?php if (array_key_exists('login', $login_errors)) {
echo '<span class="error">' . $login_errors['login'] . '</span>'; }?>

<label for="email" class="SmallHeading"><strong>Email Address</strong></label>
<?php create_form_input('email', 'text', $login_errors); ?>

<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>

<p><label for="pass" class="SmallHeading"><strong>Password</strong></label></p>
<?php create_form_input ('pass', 'password',  $login_errors);  ?>
    
<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>

Open in new window


form.functions.php

<?php

// This function generates a form INPUT or TEXTAREA tag.
// It takes three arguments:
// - The name to be given to the element.
// - The type of element (text, password, textarea).
// - An array of errors.

function create_form_input($name, $type, $errors) {
    
    // Assume no value already exists:
    $value = false;

    // Check for a value in POST:
    if (isset($_POST[$name])) $value = $_POST[$name];
    
    // Strip slashes if Magic Quotes is enabled:
    if ($value && get_magic_quotes_gpc()) $value = stripslashes($value);

// Conditional to determine what kind of element to create
    
    if (($type == 'text') || ($type == 'password') || ($type == 'checkbox')) { // Create text or password inputs.
        
        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" id="myInput"' . $name . '" size=50"';
        
        // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';

        // Check for an error:
        if (array_key_exists($name, $errors)) {
            echo 'class="error" /> <span class="error">' . $errors[$name] . '</span>';
        } else {
            echo ' />';        
        }
           
        
    } elseif ($type == 'textarea') { // Create a TEXTAREA.
        
        // Display the error first: 
        if (array_key_exists($name, $errors)) echo ' <span class="error">' . $errors[$name] . '</span>';

        // Start creating the textarea:
        echo '<textarea name="' . $name . '" id="' . $name . '" rows="5" cols="43"';
        
        // Add the error class, if applicable:
        if (array_key_exists($name, $errors)) {
            echo ' class="error">';
        } else {
            echo '>';        
        }
        
        // Add the value to the textarea:
        if ($value) echo $value;

        // Complete the textarea:
        echo '</textarea>';
        
} elseif ($type == 'checkbox') { // Create a CHECKBOX.

        // Start creating the input:
        echo '<input type="' . $type . '" name="' . $name . '" value="';

       
       // Add the value to the input:
        if ($value) echo ' value="' . htmlspecialchars($value) . '"';
        
        
        // Display the error:
        if (array_key_exists($name, $errors)) {
            
            echo ' />';        
        }
        
    } // End of primary IF-ELSE.

}// End of the create_form_input() function.

// Omit the closing PHP tag to avoid 'headers already sent' errors!

Open in new window


Thanks!

What I was pointing out is your function is expecting 3 parameters and you are only passing 2. Since the first two are hard coded, that means $login_errors is not being passed.

<?php create_form_input('email', 'text', $login_errors); ?>

Open in new window

 What you are going to have to do is right before that runs is check what the value of $login_errors is. As example on line 19 of your login.form.php above, you have that function running. Just before it, check what $login_errors is. If there are no errors, you have it set to new array with no values. Is that what is causing the error? You will have to check. Perhaps play around with setting that up with some hard coded data as if there was an actual error and see if it does not error. If it does not, then that means you will either a) have to change the function or b) on line 6 on your login.form.php set your $login_errors array with some blank keys like

$login_errors = [
   'key1' => ''
   'key2 =>''
];

Open in new window


The following is the latest code that I have on one of my include pages. login_form.inc.php. This is the form that I want to work with. I have tried this coding MANY different ways. I can't seem to come up with the right combination.

SO this one does not "SHOW or HIDE" the password field. I works as it is supposed to work otherwise. So I will get an error message when I don't put in the proper email or password and when I DO and then click SUBMIT, the information takes the user to their membership page.

// Create an empty error array if it doesn't already exist:
if (!isset($login_errors)) $login_errors = array();

// Need the form functions script, which defines create_form_input():
require_once ('./includes/form_functions.inc.php');
?>

<script>
function myFunction() {
  var x = document.getElementById('pass', 'password');
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>

<form action="Login.php" method="post" accept-charset="utf-8">

<h2>LOGIN</h2>
<?php if (array_key_exists('login', $login_errors)) {
echo '<span class="error">' . $login_errors['login'] . '</span>'; }?>

<label for="email" class="SmallHeading"><strong>Email Address</strong></label>
<?php create_form_input('email', 'text', $login_errors); ?>

<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>

<label for="pass"  class="SmallHeading"><strong>Password</strong></label>
<?php create_form_input ('pass', 'password',   $login_errors);  ?>    

<input type="checkbox" onclick="myFunction()">   SHOW PASSWORD YET ONE MORE  TIME



<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>


Open in new window

What specifically is not working?

Are you referring to the javascript, myFunction() not firing? or something else?

Are you saying the code you provided above is in a file called login_form.inc.php and it is being used in another file like

another_file.php
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>login</title>
</head>
<body>
<?php
require_once ('./includes/login_form.inc.php');
?>
</body>
</html>

Open in new window



This script does not SHOW or HIDE the password, but otherwise works. The information is submitted.

This script is in an included file called "login_form.inc.php"  which is a script that has always worked just fine, until I tried to use javascript to show or hide the password.

I have other pages with other javascript code which work. I don't know why this has to be so difficult. So I am going back to my original question. HOW do i add javascript to my PHP code that will show or hide the password. Obviously I am doing something wrong.
As I said from the start, this is a client side issue, not php.  It would really help to create an easy to duplicate test case.

From your last post, what you have that is not working are multiple id's in the getElementByID
 var x = document.getElementById('pass', 'password');

Open in new window


You only want one element here like
 var x = document.getElementById('password');

Open in new window


If you look at this test it works as expected.
https://jsbin.com/meqayacuxa/edit?html,output
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>


</head>
<body>
<input id="password" type="password" value="abc">
  <input type="checkbox" onclick="myFunction()">
  <script>
function myFunction() {
  var x = document.getElementById( 'password');
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
</body>
</html>

Open in new window



Now let's create a working test case using minimal code, only what we need to make the show/hide work via javascript but using an include file.  Create a file called test.php as the main page and the other called includeme.php.  Put them both in the same folder.

test.php
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>


</head>
<body>
<?php
 require_once 'includeme.php';
?>
</body>
</html>

Open in new window

includeme.php
<input id="password" type="password" value="abc">
  <input type="checkbox" onclick="myFunction()"> 
  <script>
function myFunction() {
  var x = document.getElementById( 'password');
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>

Open in new window


You can see the includeme.php file is exactly was I have it in the jsbin test. Sometimes, having an include file or multiple includes may cause an issue. But I don't think that is the issue here, it is your getElementByID() trying to use two id's.

Give this code a try on your own, then apply it to your current code.

Remember, your other error had to do with the lines of code for create_form_input() like below where the $login_errors variable appeared to not be passing anything. Let's keep these two issues separate. 
<?php create_form_input('email', 'text', $login_errors); ?>

Open in new window

Yes, the test.php and the includeme.php work together just fine when they are on their own. It still doesn't work with my original php code.

This was my original question to experts-exchange. I am expecting you people to tell me how to add this to my code so that it works.

The problem still seems to be the $logn_errors that is the stumbling. They are not two separate issues. Where do I put Javascript code to enable my PHP code to move the user to the next level?
Wanda, Are you using a PHP Framework like Cake? Or is this procedural code you are using?
Hey Wanda,

The problems you have all start with the the code in your create_form_input() funcrion. Until you fix that, you won't get your code working. I've stripped out most of the code to highlight your problem:

function create_form_input($name, $type, $errors) {
    // Start creating the input:
    echo '<input type="' . $type . '" name="' . $name . '" id="myInput"' . $name . '" size=50"';

Open in new window

Now, we can clearly see from this, that EVERY SINGLE FORM INPUT you create will have exactly the same ID : "myInput" (view the source of your rendered HTML if you don't beleive me!). This will break your HTML because an ID needs to be unique within a page. It also means that when you try and call the following in your Javascript:

var x = document.getElementById('pass');

This will also fail, because NONE OF YOUR INPUTS have an ID of 'pass' - they ALL have the same ID : myInput !!

That there is the funamental problem with your code. You can't move forward until you fix your create_form_input() function. Easiest way to do that would be to change the line above to:

echo '<input type="' . $type . '" name="' . $name . '" id="' . $name . '" size="50"';

Open in new window

Now when you create your inputs, they will have an ID that you can use, for example:

create_form_input('myPass', 'password', $errors);
...
let x = document.getElementById('myPass');

Open in new window

Yes, Chris,
You mentioned this previously and I didn't pay enough attention to it at that time.

I just changed my php code to get rid of the $login_errors and I still had the same problem.

SO what you said makes perfect sense to me NOW. I guess the "myInput" was a placeholder in the code that I had procured (by the way, not stole) and I was probably supposed to put something else in there quite  awhile ago.

Anyway, I will proceed with what you have said and see how it works out.


Thanks for all your help.

Okay I got rid of the includes files and everything is on one page. It APPEARS like it is going to work but I now get a "PLEASE enter your password" error.

    <form action="Login.php" method="post" accept-charset="utf-8">

    <h2>LOGIN</h2>
<p>Your browser must allow cookies in order to log in.</p>
<form action="login.php" method="post">

<p><strong>Email Address:</strong> <input type="email" name="email" size="20" maxlength="60"></p>
   
<p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>
<label for="pass"  class="SmallHeading"><strong>Password</strong></label>

<input id="password" type="password">
  <input type="checkbox" onclick="myFunction()">
  <script>
function myFunction() {
  var x = document.getElementById( 'password');
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
   
This is my last attempt.
<button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
</form>


// If it's a POST request, handle the login attempt:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   
// Validate the email address:
    if (!empty($_POST['email'])) {
        $e = mysqli_real_escape_string($db, $_POST['email']);
    } else {
        $e = FALSE;
        echo '<p class="error">You forgot to enter your email address!</p>';
    }
   
// Validate the password:
if (!empty($_POST['pass'])) {
    $p = mysqli_real_escape_string ($db, $_POST['pass']);
} else {
        $p = FALSE;
        echo '<p class="error">PLEASE enter your password!</p>';
}
Your PHP script is looking for an input with a name of 'pass':

if (!empty($_POST['pass'])) {

But your input doesn't have a name of 'pass'. In fact it doesn't have any name!

<input id="password" type="password">

You seem to take one step forward and another one back. Your input would have had a name if you'd kept your create_form_input() function as that uses the first argument to set the 'name' property

create_form_input('myPass', 'password', $errors);

That would generate an input with name of myPass:

<input id="myPass" name="myPass" type="password">

so your PHP would need to read that:

if (!empty($_POST['myPass'])) {

For your code to work, you need to make sure that your HTML input, your Javascript and your PHP are all working together.
This is my latest attempt. The user moves on to the next page but clicking the checkbox does not show or hide the password. 

<p>Your browser must allow cookies in order to log in.</p>
<form action="Login.php" method="post">
   
    <p><strong>Email Address:</strong> <input type="email" name="email" size="20" maxlength="60"></p>
   
    <p><a href="ForgotPassword.php"><h2>Forgot Your Password?</h2></a></p>
   
    <strong>Password:</strong> <input type="password"  name="pass">
    <input type="checkbox" onclick="myFunction()">
   
    <button class="button" style="vertical-align:left"><span>Login &rarr;</span></button>
    </form>
<div>
   
<script>
function myFunction() {
  var x = document.getElementById( 'pass');
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>

Hmmm. You keep making your own changes in the hope that it will work. We're trying to give you the answer, but you keep deviating from what we're telling you.

You've now given the input an name, but for some unknown reason, you've decided to remove the ID ! Why did you do that ?

Look, here's the thing. When you submit an input, the PHP script needs the 'name' to read it's value, so you need that. Your Javascript on the other hand has this:

var x = document.getElementById( 'pass');

So that's clearly trying to get to the input by an ID of 'pass'. It therefore stands to reason, that your code won't work if you've removed the ID.

You need your input to have an ID and a Name - which it would have had if you'd kept with your create_form_input() function. If you're doing this manually, then you need something like this:

<input type="password"  name="pass" id="pass">

Now your Javascript can hook into the ID, and your PHP can hook into the name:

// PHP
$_POST['pass']; // get the input with a NAME of pass

// JS
document.getElementById( 'pass'); // get the input with an ID of pass
Okay, well let's put it this way. When I submit something on this site, what I have submitted isn't the only thing that I have tried. I have probably tried this particular one about ten different ways, and I am not getting it to work, and then give up for the time being.

I went back to the older code with the create_form_input() and I could not get it to work.

Believe I always think that I understand what is being said but obviously I am doing something incorrectly. SO I am going to take a bit of a break and will get back to experts-exchange later today.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Please close this question.
Wanda, to close the question, you have some choices. You can select one or more comments as the solution. Or if you found your own solution, click the link above the last comment box, "I found my own solution" then in the updated comment box, let everybody know what worked. Clicking the submit button selects your comment as the solution. After that, you can still mark other comments has helpful or assisted solution if you like.