TerranRich
TerranRich

Reputation: 1298

Return value for function containing jQuery $.post() function

I understand that AJAX is asynchronous, and all that. But I have the following code:

function doesUsernameExist(element)
{
    // Check via AJAX (POST) if username already exists in the database
    var funcReturned = null;
    $.post(
        '_ajax_checkexist.php',
        {
            var: 'username',
            value: element.value
        },
        function(data) {
            funcReturned = (data.toLowerCase() == 'exists');
        },
        'data'
    );
    return funcReturned;
}

I understand why the function isn't returning a value properly, but what can I use as a workaround? This is for the Validity plugin, which requires a boolean returned by the doesUsernameExist function. I can't do the usual workaround of having the $.post function alter some HTML element. It needs to return true/false to doesUsernameExist.

What kind of workaround can I use? I'm stumped by this.

Upvotes: 2

Views: 9591

Answers (2)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

You could return a value if the call is synchronous. Here you have an example:

Solution for synchronous mode:

function doesUsernameExist(element)
{
    // Check via AJAX (POST) if username already exists in the database
    var funcReturned = null;
    $.ajaxSetup({async: false});
    $.post(
        '_ajax_checkexist.php',
        {
            var: 'username',
            value: element.value
        },
        function(data) {
            funcReturned = (data.toLowerCase() == 'exists');
        },
        'data'
    );
    $.ajaxSetup({async: true});
    return funcReturned;
}

The problem with your code, is that while the $.post is executing, the function continues it's execution (that's asynchronous), so will return null before your $.post ended.

Solution for asynchronous mode:
Using an asyncrhonous call, you cannot return a value, but can call callbacks or execute code just there. This could be an async solution:

function doesUsernameExist(element)
{    
    var funcReturned = null;
    $.post( //This post is asynchronous
        '_ajax_checkexist.php',
        {
            var: 'username',
            value: element.value
        },
        function(data) {
            funcReturned = (data.toLowerCase() == 'exists');
            userExistanceCallback(funcReturned);
        },
        'data'
    );
    //We don't return anything
}

function userExistanceCallback(funcReturned){
   if(funcReturned == true)
       alert("User exists!!");
   else
       alert("User does not exist!!");
}

Hope this helps. Cheers

Upvotes: 13

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

If this is for validation purposes you will find that the jquery.validate plugin and its remote rule are perfectly adapted for what you are trying to achieve.

So, instead of writing doesUsernameExist functions and worrying about asynchronousness of AJAX and how to return values you will write validation rules for your form (which in fact is the final goal of the exercise => focus on the business and leave the plumbing to plugins):

$('#id_of_some_form').validate({
    rules: {
        password: {
            required: true
        },
        username: { 
            remote: '_ajax_checkexist.php'
        }
    }
});

Upvotes: 2

Related Questions