开发者

How can I make this AJAX/PHP work?

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['开发者_JAVA技巧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>


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.


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.


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.


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


try this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜