Alex Rivera | Logout

How do I do a jQuery blocking AJAX call without async = false?

Asked 2012-06-16T10:57:40.150
14

I have a page which does AJAX validation of an email before continuing on to the next page, using the HTML5 setCustomValidity() method [using the webshims library for older browsers].

For this to work, I set the async option to false in the $.ajax() call to make it synchronous, blocking the page pending the AJAX response, as otherwise the form submits before the ajax call returns, rendering the validation ineffectual.

<script>
  function validateEmailRegistered(input) {
    if (input.setCustomValidity === undefined) return;
    var err = 'Email address not found';
    $.ajax({
      url: 'email-is-registered.php', 
      data: { email: input.value }, 
      async: false, 
      success: function(data) {
        var ok = data=='true';
        input.setCustomValidity(ok ? '' : err)
      }
    });
  }
</script>

<form method="get" action="nextpage.php">
  <input name="email" id="email" type="email" required
    onChange="validateEmailRegistered(this)">
  <button type="submit">go</button>
<form>

I see that the async option is to be deprecated as of jQuery 1.8.

How can I achieve this blocking action without the async option?

Edit
Report

1 Answer

0

I assume you will be doing full form validation on submit anyway, so perhaps it's no problem if the as-you-type email validation is interrupted, and precedence given to the form submission.

I think what I'd do is abort the 'validateEmailRegistered' AJAX request when the user submits the form. Then, perform full server-side form validation as usual - including email validation.

My understanding of as-you-type validation is that it's a nicety, not a substitute for validating the form when it is submitted. So it doesn't make sense to me for it to block the form submission.

answered 2012-06-16T11:24:57.370

Your Answer