如何使这个AJAX/PHP工作?

时间:2021-07-13 04:30:12

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.

因此,我对AJAX并不陌生(对PHP来说并不陌生),我正在尝试使用AJAX创建一个登录来查询PHP文件。这就是我要用的代码。

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

我有三个文件。第一个是login_form.php。它包含登录表单…

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

下一个loginsender.js。这是我用来发送给PHP脚本的JavaScript/AJAX文件…

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,我用它来处理实际的登录。

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

总而言之,目标是让用户在login_form中输入他们的用户名和密码组合。php并提交它,触发loginsender。js(和formValidator()方法)。然后将查询PHP登录脚本,该脚本将测试有效的用户/pass组合,然后在会话中设置它(如果登录失败,则不设置)。问题是,无论我输入什么组合,都不会发生任何事情,页面会在单击submit后刷新,但仅此而已。

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

更新1:我已经编辑了我的login_form页面,我只是简单地将formValidator函数放入到脚本中,这样我就可以更容易地查看而不是在文档之间切换。

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>

5 个解决方案

#1


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:

将表单html行更改为:

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

返回false;告诉它不要做它要做的任何事情。

#2


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.

如果不希望表单提交操作刷新页面,请从onsubmit脚本返回false。否则,浏览器将按照您在

: HTTP POST中告诉他的那样做。

#3


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.

我认为OnSubmit()函数已经执行,而且表单已经提交!你会得到一个空白的页面这是php脚本的输出。

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

不要把它做成html格式,它应该可以正常工作。

#4


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

除此之外,你的代码很好。

#5


0  

try this

试试这个

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

#1


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:

将表单html行更改为:

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

返回false;告诉它不要做它要做的任何事情。

#2


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.

如果不希望表单提交操作刷新页面,请从onsubmit脚本返回false。否则,浏览器将按照您在

: HTTP POST中告诉他的那样做。

#3


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.

我认为OnSubmit()函数已经执行,而且表单已经提交!你会得到一个空白的页面这是php脚本的输出。

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

不要把它做成html格式,它应该可以正常工作。

#4


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

除此之外,你的代码很好。

#5


0  

try this

试试这个

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