RaviKant Hudda RaviKant Hudda - 6 months ago 23
jQuery Question

How to stop redirection in Php if validation is failed?

I am having problem in signup.php page. I want if information is already existing in database then this page should stop redirecting to next page and show alert box. Now the problem is I tried the following code snippet of jquery but this did not work in my case.I googled about this and come with the following solution but this did not work.

Jquery Code

function validate()
{
var email =$('#email').val();
var mobile = $('#mobile').val();

$.post("check_user.php",{ email: email,mobile:mobile},

function(result){
if(result == "0"){
alert('This email is already registered with us. Please try another.');
return false;
}
else
{
return true;
}
});
}


Html code is given below where I am calling this jquery function

HTML Code

<form id="form1" autocomplete="on" action='/marammut_new/test.php'
method="post" enctype="multipart/form-data" onsubmit="return validate()">
...
</form>

Jai Jai
Answer

As this is a asynchronous call and it validates the form asynchronously and before the response it would get the function gets executed. Better to stop the form submission and submit it explicitly:

function validate() {
  var email = $('#email').val();
  var mobile = $('#mobile').val();

  $.post("check_user.php", { email: email, mobile: mobile },function(result) {
      if (result == "0") {
        alert('This email is already registered with us. Please try another.');
      } else {
        $('#form1')[0].submit();
      }
    });
  return false; // stop it here
}