Question

I am using ajax to login user but this script is not working. When i call login function to execute nothing happens..

function login() {
            var login = new XMLHttpRequest;
            var e = document.getElementById("email").value;
            var p = document.getElementById("password").value;                  
            var vars = "email=" + e + "&password=" + p;
            login.open("POST", "http://example.com/app/login.php", true);
            login.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            login.onreadystatechange = function(){
                if (login.readyState == 4 && login.status == "200") {
                    var response = login.responseText;
                    //document.getElementById("status").innerHTML = response;
                }
                document.getElementById("status").innerHTML = "Loggin in....";
                login.send(vars);
                if (response == "Sucess") {
                    window.location.replace("/logged.html");
                }
                else {
                    document.getElementById("status").innerHTML == "Login Failed";                    
                }
            }
        }

login.php contains following codes

require_once('../db_/connection.php');//Holds connection to database
$email = mysqli_real_escape_string($con, $_POST['email']);//Sanitizing email
$pass = md5($_POST['password']);//Hashing password

$sql = "SELECT id FROM users WHERE email='$email' AND password='$pass' LIMIT 1";
$query = mysqli_query($con, $sql);
$check = mysqli_num_rows($query);

if($check < 1){
    echo "fail";
    //mysqli_close($con);
    exit();
}
else{
    echo "Sucess";
    //mysqli_close($con);
    exit();
}

Calling login function does not execute the code.

Was it helpful?

Solution

  • Line 2: The parentheses are missing after new XMLHttpRequest
  • Line 15: Your if (response == "Sucess") { ... } is misspelled and it gets executed before the ajax request is returned, because it's asynchronous

I made a working version at JSFiddle for you: http://jsfiddle.net/eRv83/

You might find the MDN referrence helpfull: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top