1

So I'm new to AJAX (not as new to PHP), and I'm trying to create a login using AJAX to query the PHP file. So, this is the code I'm trying to use.

I have three files. The first one is login_form.php. It contains the login form...

<html>
    <head>
        <title>Log In</title>
        <script language="javascript" src="loginsender.js" />
    </head>
    <body>
        <form method="post" name="loginfrm" onsubmit="formValidator()">
            <p id="hint"></p>
            <label for="username">Username:</label><input type="text" name="username" id="username" />
            <label for="password">Password:</label><input type="password" name="password" id="password" />
            <input type="submit" name="submit" value="Log In" />
        </form>
    </body>
</html>

The next loginsender.js. This is the JavaScript/AJAX file I'm using to send to the PHP script...

function formValidator()
{
    if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
    {
        msg = "Please enter a valid username/password."
        document.getElementById("hint").innerHTML=msg;
    }
    else
    {
        if (window.XMLHttpRequest)
        {
            xmlhttp = new XMLHttpRequest();
        }
        else
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function()
        {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById("hint").innerHTML = xmlhttp.responseText;
            }
        }
    }

    var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
    xmlhttp.open("post", "login.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);
}

The last one is login.php, which is what I'm using to handle the actual logging in...

<?php
session_start();

require_once("includes/mysql.inc.php");
require_once("includes/functions.inc.php");

$username = sanitize($_POST['username'], true);
$password = sanitize($_POST['password'], true);

$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) != 1) // no such user exists
{
    echo 'Sorry, no such user exists';
    logout();
    die();
}
$userData = mysql_fetch_assoc($result);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password));

if ($hash == $userData['password'] && $username == $userData['username']) // successful log in
{
    validateUser($userData['username']); // set session data
    echo '<meta http-equiv="refresh" content="2; url=index.php" />';
}
else
{
    echo 'Sorry, but you entered an incorrect username/password.';
    logout();
    die();
}

?>

All in all, the goal is to have the user enter their username and password combination in login_form.php and submit it, triggering loginsender.js (and the formValidator() method). This then will query the PHP login script, which will test for a valid user/pass combo, then set it up in the session (or not, if the log in failed). The issue is, no matter what combination I enter, nothing happens, the page refreshes upon clicking submit, but that's it.

**UPDATE 1: I have edited my login_form page, I've simply put the formValidator function into the script to start with, that way its easier for me to look at rather than flipping between documents.

I also implemented some of the suggestions that were made.

Here it is:

<html>
    <head>
        <title>Log In</title>
        <script type="text/javascript" language="javascript">
        function formValidator()
        {
            if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
            {
                msg = "Please enter a valid username/password."
                document.getElementById("hint").innerHTML=msg;
            }
            else
            {
                if (window.XMLHttpRequest)
                {
                    xmlhttp = new XMLHttpRequest();
                }
                else
                {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange = function()
                {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    {
                        document.getElementById("hint").innerHTML = xmlhttp.responseText;
                    }
                }
            }

            var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
            xmlhttp.open("post", "login.php", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.setRequestHeader("Content-length", params.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.send(params);
        }
        </script>
    </head>
    <body>
        <p id="hint"></p>
        <form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
            <label for="username">Username:</label><input type="text" name="username" id="username" />
            <label for="password">Password:</label><input type="password" name="password" id="password" />
            <input type="submit" name="submit" value="Log In" />
        </form>
    </body>
</html>
1
  • You should modify your login.php, you can't meta refresh through ajax request. You have to meta-refresh / page-redirect process after getting ajax response at javascript code block.
    – mahadeb
    Sep 29, 2011 at 7:22

5 Answers 5

2

It doesn't look like you're preventing the default 'submit' action from happening, which since you haven't defined a action for the form is to just POST back to the current page.

Change your form html line to:

<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">

The return false; tells it to NOT do whatever it was going to do for that action.

4
  • When I change my code to that, it just redirects back to the login_form page, without displaying the updated error message.
    – Alper
    Sep 29, 2011 at 7:32
  • maybe you have missed any " at the above line
    – mahadeb
    Sep 29, 2011 at 7:36
  • Nope, I'll post my updated code as an edit to my question. I'll just call it Update 1.
    – Alper
    Sep 29, 2011 at 7:37
  • @Jacob, this could be because your method or some other JS is erroring. Open up Firebug, do you see anything? (Also put a console.log in the top of your method, just to make sure it's getting entered)
    – Dave
    Sep 29, 2011 at 7:42
1

If you don't want the Form-submit-action to refresh the page, return false from your onsubmit script. Otherwise, the browser will do exactly what you tell him in the <form>: a HTTP POST.

0

I think the OnSubmit() function is executed and also the form is really submitted! So you get a blank page which is the output of php script.

Don't make it a html-form and it should work fine.

0

You need to write this to prevent form refresh..

<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">

other than this, your code is fine..

0

try this

<input type="submit" name="submit" value="Log In" onclick="formValidator(); return false;"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.