1

I'm trying to create a basic login page. People enter a username and password. It will check with a database. If they can validate their credentials, they can advance to a different page. If not, it will display an error message. Here's the line I'm having problems with:

else {
// Print login failure message to the user and link them back to your login page
echo '<script>document.getElementById("error").innerHTML = "Invalid username or password."    </script>';
   }

When I paste everything in between the quotes (omitting the script tags, of course) directly into the console, everything works as it should. However, whenever I try and echo it out through my PHP file, nothing happens. Any help would be greatly appreciated.

Here's the complete file:

<?php
session_start(); // Can't forget to start a session!

//Connect to the database
include_once "connect/connect_to_mysql.php";

if ($_POST['username'] || ($_POST['password'])) {
$username = ($_POST['username']);
$password = ($_POST['password']);
// $password = preg_match("[^A-Za-z0-9]", "", $_POST['password']); // only numbers and letters
// $password = md5($password); // Hash the password for security!

// Query the database and then convert all database data into variables.
$sql = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password' AND   activated='1'"); 
$login_check = mysql_num_rows($sql);
if($login_check > 0){ 
while($row = mysql_fetch_array($sql)){ 

    // Get member ID into a session variable
    $id = $row["id"];

    //session_register('id'); 
    $_SESSION['id'] = $id;

    // Get member username into a session variable
    $username = $row["username"];

    // Get username into a session variable
    $_SESSION['username'] = $username;

    // Update the 'lastlogin' field to current date/time
    mysql_query("UPDATE Users SET lastlogin=now() WHERE id='$id'"); 

    // If successful, redirect to profile
    header("location: main.php"); 
    exit();
 }
} else {
// Print login failure message to the user and link them back to your login page
echo '<script>document.getElementById("error").innerHTML = "Invalid username or password."</script>';
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Timeclock Login</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
</head>
<body>
<div class="largetext">
    Timeclock<span style="font-weight:300;">Login</span>
</div>

<div class="loginbox">
    <form action="index.php" method="post" enctype="multipart/form-data" name="login" id="login">
        <div id="error"></div>
        <label><input type="text" name="username" placeholder="Username"></label>
        <label><input type="password" name="password" placeholder="Password"></label>
        <input type="submit" name="Login" class="loginbutton" value="Log in"></input>
    </form>
</div>
</body>
</html>
  • 1
    You can not reference an element before it is rendered to the page. – epascarello Nov 25 '14 at 03:58
  • If you want help with client–side code or markup, post what the client gets (e.g. show source), not the server code that produces it. – RobG Nov 25 '14 at 03:58
  • can you change the line to echo ''; and see if it works – Satya Nov 25 '14 at 03:58

2 Answers2

3

The issue that you are having is related to DOM rendering. When you are echoing the <script> tag to the browser, the browser has not yet fully rendered the Document Object Model. So, what is happening is the call to document.getElementById("error") is not retuning any results, and therefore the call to .innerHtml accomplishes nothing.

What you need to do is defer the call to document.getElementById("error") until after the DOM is available. In common JavaScript libraries like jQuery, a utility method to defer parsing of JavaScript is provided:

$(document).ready(function() {
    document.getElementById("error").innerHTML = "Invalid username or password.
});

This can be done in vanilla JavaScript too. If you don't care about IE8 or earler:

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("error").innerHTML = "Invalid username or password.
});
Community
  • 1
  • 1
Ben Harold
  • 5,634
  • 5
  • 43
  • 69
  • Thank you so much, Ben! I really appreciate the help. Let's just say that JavaScript isn't one of my strong points. ;) I need to work more with JQuery too. Your script worked perfectly for me. A million thanks! – Bryce Matheson Nov 25 '14 at 04:14
-1
<?php
session_start(); // Can't forget to start a session!

//Connect to the database
include_once "connect/connect_to_mysql.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Timeclock Login</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
</head>
<body>
<div class="largetext">
    Timeclock<span style="font-weight:300;">Login</span>
</div>

<div class="loginbox">
    <form action="index.php" method="post" enctype="multipart/form-data" name="login" id="login">
        <div id="error"></div>
        <label><input type="text" name="username" placeholder="Username"></label>
        <label><input type="password" name="password" placeholder="Password"></label>
        <input type="submit" name="Login" class="loginbutton" value="Log in"></input>
    </form>
</div>
<?php
if ($_POST['username'] || ($_POST['password'])) {
$username = ($_POST['username']);
$password = ($_POST['password']);
// $password = preg_match("[^A-Za-z0-9]", "", $_POST['password']); // only numbers and letters
// $password = md5($password); // Hash the password for security!

// Query the database and then convert all database data into variables.
$sql = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password' AND   activated='1'"); 
$login_check = mysql_num_rows($sql);
if($login_check > 0){ 
while($row = mysql_fetch_array($sql)){ 

    // Get member ID into a session variable
    $id = $row["id"];

    //session_register('id'); 
    $_SESSION['id'] = $id;

    // Get member username into a session variable
    $username = $row["username"];

    // Get username into a session variable
    $_SESSION['username'] = $username;

    // Update the 'lastlogin' field to current date/time
    mysql_query("UPDATE Users SET lastlogin=now() WHERE id='$id'"); 

    // If successful, redirect to profile
    header("location: main.php"); 
    exit();
 }
} else {
// Print login failure message to the user and link them back to your login page
echo '<script>document.getElementById("error").innerHTML = "Invalid username or password."</script>';
}
}
?>


</body>
</html>

Try the above. By this the element will be loaded before the script executes.

Rajesh
  • 139
  • 6
  • Just because you output HTML to the browser does not mean the DOM is ready. – Ben Harold Nov 25 '14 at 04:09
  • the parsing of login failure script itself will happen after the `#error` div is loaded. – Rajesh Nov 25 '14 at 04:10
  • oh okay. Can you check this in your console and advice me please. http://plnkr.co/edit/5zm9k6Alfvb1b78lF6ei – Rajesh Nov 25 '14 at 04:27
  • My previous comment was flawed, I had a typo in my JavaScript. It appears my assertion is partially incorrect. Nevertheless, the DOM tree *might* be ready, depending on the resources needed to render the page. [This question has a superb answer that may shed a bit of light on my thinking.](http://stackoverflow.com/questions/1438883/jquery-why-use-document-ready-if-external-js-at-bottom-of-page) – Ben Harold Nov 25 '14 at 04:33
  • Please check [this](http://plnkr.co/edit/5zm9k6Alfvb1b78lF6ei). the text is over written. Because the element is loaded before the script executes. Your link also saying the same thing we don't have to put document.ready when we place our script at the bottom of the body – Rajesh Nov 25 '14 at 11:42
  • The answer you are pointed is also suggesting the same as i suggested. We don't need `document.ready` if we place the script at the bottom of the page. So all the elements are rendered before parsing the script. @BenHarold – Rajesh Nov 30 '14 at 07:52