Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return False not working inside jQuery.ajax

Tags:

jquery

ajax

P.S.: Read "EDITED on 2019-06-29":

I have a webform for updating user information, and when he updates his email a verification is performed via ajax() so that he is warned if the new email address is already in use by another user.

I'm trying to cancel the form submission when the email is in use, but return false; doesn't work.

Any other return false; within if statements are working fine, the problem is only with this one inside the jQuery.ajax() call.

Here's the actual code:

var email = jQuery('#email').val();
jQuery.ajax({
    type : 'GET',
    url : '/ajax/verify-email.php?email=' + email,
    success : function( d ) {
        if( d == '1' ) {
            alert('Another user is using this email');
            jQuery('input[name="email"]').focus();
            return false; // this guy over here is not working!!!!
        }
    }
});

Does anyone have a solution?

EDITED on 2019-06-29

When I asked this question back in 2012 I wasn't aware of Promises in Javascript, neither knew about "$.when" (even though added 3 years later of this question) to handle asynchronous requests alongside $.ajax.

Today, you can handle the same scenario easily, as this:

let email = $('#email').val();
$.when(
  $.ajax({
    type : 'GET',
    url : `/ajax/verify-email.php?email=${email}` 
  })
 .then(function(d) {
   alert('Another user is using this email');
   $('input[name="email"]').focus();
});
// your code continues from here as desired...
like image 235
Gilberto Albino Avatar asked Feb 23 '12 22:02

Gilberto Albino


People also ask

How do you return false in AJAX?

val() }, success: function(result) { return false; } });

What is jqXHR in AJAX?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.

How does AJAX work?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.


1 Answers

The A in AJAX is actually very important. It stands for Asynchronous. This means that you trigger a request to the server which might take some time to process and you get a response later. This response happens inside the success callback. But since this happens much later than the actual form submission, your form has actually been already submitted before the response comes back. So returning false from an AJAX success callback makes no sense whatsoever. What you want to do is to return false from the submit handler of your form. Let's see how we could implement this.

You could subscribe to the .submit handler of the form and send an AJAX request to verify whether the email has already been taken or not and if it is not taken manually trigger the submission of the form inside the success AJAX callback:

$('form').submit(function() {
    // we send an AJAX request to validate the unicity of the email
    $.ajax({
        url: '/ajax/verify-email.php',
        type: 'POST',
        data: { email: $('#email').val() },
        // we set the context to the form so that inside
        // the success callback 'this' points to the form
        context: this,
        success: function(result) {
            if (result != '1') {
                // If the server send something different than 1
                // we know that the email is unique and trigger
                // the submission of the form using the underlying
                // DOM element to avoid calling the .submit handler
                // recusrively
                this.submit();
            } else {
                // The email is not unique => we are informing
                // the user that the email is already in use
                alert('Another user is using this email');
                $('#email').focus();
            } 
        }
    });

    // we cancel the normal submission of the form    
    return false;
});

Also never rely on client side validation. Make sure that you are performing the email is unique check once the form has been successfully submitted to the server. If you are using a SQL database that's easily achieved with a unique constraint on your Email field.

like image 83
Darin Dimitrov Avatar answered Sep 30 '22 13:09

Darin Dimitrov