简体   繁体   中英

Authentication using AJAX & PHP

I make a simple program to simulate authentication using AJAX and PHP. The following is my code. It will redirect to "/?" but nothing happened. I tried to use checkLogin(); return false; checkLogin(); return false; in onclick event but it didn't work.

index.php

<script type="text/javascript" src="validation.js"></script>
<form>
    <p>
        <label>Username <abbr title="Required">*</abbr></label>
        <input id="usernamelogin" type="text" value="" />
    </p>
    <p>
        <label>Password <abbr title="Required">*</abbr></label>
        <input id="passwordlogin" type="text" value="" />
    </p>                
    <p>
        <input id="login" type="submit" value="Login" onclick="checkLogin()" />
    </p>
</form>

validation.js

function checkLogin(){
    var u = document.getElementById("usernamelogin").value;
    var p = document.getElementById("passwordlogin").value;

    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }
    else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onReadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            if(xmlhttp.responseText == u){
                alert(':)');
            }
            else{
                alert(':(');
            }
        }
    }

    xmlhttp.open("GET", "login.php?u=" + u + "&p=" + p, true);
    xmlhttp.send(); 
}

login.php

<?php
    $u = $_GET['u'];
    $p = $_GET['p'];

    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $db = 'db';

    $con = mysql_connect($host, $user, $pass);
    if(!$con) die("Could not connect: " . mysql_error());

    mysql_select_db($db, $con);
    $query = "select username from login where username = '" . $u . "' and password = '" . $p . "'";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    echo $row['username'];
    mysql_close($con);
?>

I change the following code

xmlhttp.onReadystatechange

to

xmlhttp.onreadystatechange

and it works. And also use onclick="checkLogin(); return false;" in input type="submit" .

What you can do is remove the onclick event from the input type="submit" and add it to the form:

<form onsubmit="return checkLogin()">

To let this work, you have to add

return false

to your javascript function, right before you close the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM