1

In the following code, the ajax call works and isTaken is updated properly. But return isTaken executes before the ajax call completes so it always returns the initial false setting. async = true is deprecated so how do I wait for the ajax call to finish before returning a properly updated isTaken response?

    $.validator.addMethod("checkExists",
        function (value, element) {

            var email = $("#email").val();
            var data = {email: email};

            var isTaken = false;
            $.ajax({
                type: "POST",
                url: "http://localhost/CFBserver/check_email.php",
                data: data,
                success: function (response) {
                    isTaken = (response == 1) ? true : false;
                }
            });
            return isTaken;
        },
        "This username is already taken! Try another."
        );
dru37
  • 199
  • 1
  • 11

1 Answers1

0

Use jQuery.when() for this, which waits for the passed AJAX calls to finish before completing the callback function.

$.validator.addMethod("checkExists",
    function (value, element) {

        var email = $("#email").val();
        var data = {email: email};

        $.when(
            return $.ajax({
                type: "POST",
                url: "http://localhost/CFBserver/check_email.php",
                data: data
            });
        ).done(function(response) {
            return response == 1; // returns true is response is 1, false otherwise
        });
    },
    "This username is already taken! Try another."
    );

I have also simplified your code a bit by returning the boolean value according to the if statement you had.

I would get this AJAX call out of your function and make it a separate one - this way the code will look better and the call can be made from another places.

$.when(checkMail).done(function(response) {
    return response == 1; // returns true is response is 1, false otherwise
});

// Outside of validator function...

function checkMail() {
     return $.ajax({
        type: "POST",
        url: "http://localhost/CFBserver/check_email.php",
        data: data
    });
}

Furthermore, would you also want to handle errors in your AJAX call, use then instead of done and provide two functions as callbacks: one for success, and one for failure:

$.when(checkMail).then(function(response) {
    // Function gets called as 'success' from AJAX
    return response == 1;
}, function (errorResponse) {
    // Function gets called as 'error' from AJAX
    // return false; // or
    // return "Error when checking email: " + errorResponse;
});
Siavas
  • 4,992
  • 2
  • 23
  • 33