Bryce Matheson
Bryce Matheson

Reputation: 23

JavaScript works in console, but not on my page

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>

Upvotes: 1

Views: 2406

Answers (2)

Ben Harold
Ben Harold

Reputation: 6432

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.
});

Upvotes: 3

Rajesh
Rajesh

Reputation: 139

<?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.

Upvotes: -1

Related Questions