Skip to content Skip to sidebar Skip to footer

Ajax Login Form Gets Submitted Even If Info Is Invalid

I have called the validate function onclick for the submit button. HTML

Solution 1:

Try this.It is working. The reason it didn't work is because you were not checking the status and readystate of the ajax request.

functionvalidate() {

   var xhr;
     if (window.XMLHttpRequest) {
        xhr = newXMLHttpRequest();
    }
    elseif (window.ActiveXObject) {
        xhr = newActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        thrownewError("Ajax is not supported by this browser");
    }

    var username = document.getElementById("username_input").value;
    var password = document.getElementById("password_input").value;
    xhr.open('POST', 'validate.php',true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("username=" + username + "&password=" + password );   
    xhr.onreadystatechange = function () {
 if (xhr.readyState==4 && xhr.status==200)   //this is needed
    {
    var data=xhr.responseText.trim();
            document.getElementById("login_feedback").innerHTML = data;
            if (data=='correct'){
                     document.getElementById("loginform").submit();
                }
    }

    } 
   }

Hope this helps, Thank you

Solution 2:

your not validating anything in your validate function. at least add a basic check as follows to see if the variables are empty or not.

var username = document.getElementById("username_input").value;
var password = document.getElementById("password_input").value;
if (username.trim() == "" || password.trim() == "") returnfalse;

Post a Comment for "Ajax Login Form Gets Submitted Even If Info Is Invalid"