0

I am using Ajax and Php to validate a user's login.. But form onsubmit is not working..

<form action="loggedin.php" onsubmit="return test()" method="post">

Javascript

function test(){
    var a = document.getElementById("email").value;
    var b = document.getElementById("pwd").value;                
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
        var resp = this.responseText;
        if(resp != "Correct"){
            document.getElementById("email").value = "";
            document.getElementById("pwd").value = "";
            document.getElementById("passdiv").style.display = "block";
            return false;
        }
        else{
            return true;
        }
    }
    else{
        return false;
    }
    };
    xmlhttp.open("POST","check.php",true);
    xmlhttp.send("email=" + a + "&passwd=" + b);
}

Why is it not working?

  • 1
    You're trying to prevent the form submitting by return a value from `onreadystatechange` and then capturing it in `onsubmit` … but the function you are calling from `onsubmit` is `test` and `test` doesn't have a `return` statement of its own. – Quentin Jul 24 '18 at 13:50
  • @AnsBilal — No! Returning a value from a function defined by an intrinsic event attribute is how you prevent the default action for the event occurring. The link you provide doesn't seem relevent either. – Quentin Jul 24 '18 at 13:55
  • then it should return some value – Ans Bilal Jul 24 '18 at 13:56
  • @AnsBilal — Yes, and my earlier comment explains why the OP (presumably) thinks it should and why it doesn't. – Quentin Jul 24 '18 at 14:04
  • @Quentin As you said that test does not have its return of its own, on updating it as in the code, it is still not working – Handmadegifts co Jul 24 '18 at 14:12
  • @Handmadegiftsco — Your edit just puts more return statements inside the `onreadystatechange` function. `test` still doesn't have one of its own. – Quentin Jul 24 '18 at 14:13
  • @Quentin Okay.. Just got my mistake..Thanks.. – Handmadegifts co Jul 24 '18 at 14:16

1 Answers1

-1
onsubmit="test()"

Don't use return.

zanmato
  • 102
  • 1
  • 7