WitchKing17
WitchKing17

Reputation: 184

Validating username/password through Ajax

I am trying to use Ajax to validate a username and password stored in a php document on a server. The usernames and passwords are pre stored in the document.

On my HTML page is a field for the username, and a field for the password. Then, when they click the Log-In button it calls the following function:

    function checkLogin() {
        var user = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        var data = "userName=" + user + "&password=" + password;

        var request = new XMLHttpRequest();

        request.open("POST", "check.php", false);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.send(data);

        if (request.status === 200) {
            window.open("test.html");
        } else {
            var messageSpan = document.getElementById("response");

            var responseJson = JSON.parse(request.responseText);
            messageSpan.innerHTML = "Your password of " + responseJson["password"] + " was not corerct. Please try again.";
        }
    }

The problem I'm having is that it never gets to the else if the username/password are incorrect. Even if there's nothing in the fields, it opens the new page. What am I doing wrong for it to think that all data is correct?

NOTE: The above code is for testing purposes only, and won't actually be used when publishing the web page. I just want to see what's happening and get it to work before moving on. Thanks.

Upvotes: 1

Views: 4256

Answers (3)

Navid
Navid

Reputation: 910

Most likely your check.php echos out true or false on response in some cases you echo out user ID on success. Anyways, your response code is 200 for successful server communication. Examine request.responseText in case of getting 200.

if (request.readyState == 4 && request.status === 200) { 
var responseJson = JSON.parse(request.responseText); 
if (responseJson['success'] == 1){
    window.open("test.html"); 
} else { 
    var messageSpan = document.getElementById("response"); 
    messageSpan.innerHTML = "Your username and password combination was incorrect."; 
}} else {
//For debugging purpose add an alert message here. alert(request.status);
messageSpan.innerHTML = "A server connection error occurred!";  }

It's noticeable that you are sending back json response. So you may add a node called success whith value of true or false to examine logged in success. It's not a good practice to show password in response message though.

Upvotes: 1

Ashan
Ashan

Reputation: 479

simply you can use ajax like this,

   <script>
    function checkLogin() {

    var user = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    $.ajax({
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    //progress        
                    xhr.upload.addEventListener("progress", function(e) {
                        //progress value e                            
                    }, false);
                    return xhr;
                },
                type: "POST",
                url: "check.php",
                data: {'userName' : user , 'password' : password},
                dataType:json,
                success: function(msg) {
                   //when success //200 ok
                 if(msg.status=="done"){
                 window.open("test.html");                      
                  }else{    
    var messageSpan = document.getElementById("response");
    messageSpan.innerHTML = "Your password of " + msg.password+ " was incorrect.";
}

                },
            error: function(jqXHR, textStatus, errorThrown) {
               //when error   
            }
        });
}
</script>

your php server side like this,

    //$status="fail" or "done"
    //success must be always success
$respond=array("success"=>"success","status"=>$status,"password"=>$password);
   echo json_encode($respond);
   exit;

I think this useful for you !

Upvotes: 0

FastTurtle
FastTurtle

Reputation: 1787

Well the problem is you are getting status 200 from your check.php every time. In your check.php you need to do some thing like

// let validate() be function that validates your username/password     


// and returns true/false on validation

if(validate()){
  http_response_code(200);
} else {
  http_response_code(401);
}

hope it helps

Upvotes: 0

Related Questions