Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return an AJAX-retrieved value to the parent function of the current function in JavaScript?

I have the following JavaScript (and jQuery) code:

function checkEmail(email) {
    if (email.length) {
        $.getJSON('ajax/validate', {email: email}, function(data){
            if (data == false) {
                // stuff
            }
            return data;
        })
    }
}

I want the anonymous function to return data to the parent function, checkEmail(). I tried doing something like this:

function checkEmail(email) {
    if (email.length) {
        var ret = null;
        $.getJSON('ajax/validate', {email: email}, function(data){
            if (data == false) {
                // stuff
            }
            ret = data;
        })
        return ret;
    }
}

But of course this won't work because the $.getJSON() call is asynchronous, so it will return ret before the GET request is finished.

Any thoughts here?

Thank you!

like image 765
frontendbeauty Avatar asked Sep 22 '09 18:09

frontendbeauty


People also ask

How do I return AJAX result?

This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax. Request(postUrl, { method: 'post', postBody: postData, contentType: 'application/x-www-form-urlencoded', onComplete: function(transport){ if (200 == transport.

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

How does AJAX return success data?

The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds. The function takes three parameters, namely: The data returned from the server, formatted according to the dataType parameter, or the dataFilter callback function.

What is .done function in AJAX?

The done() function is given a function as parameter. The callback function passed as parameter to the done() function is executed if the AJAX request succeeds. The callback function gets three parameters: data , textStatus and jqXHR . The data parameter is the data returned by the server.


2 Answers

Generally, the best way to handle this type of issue is to use some form of callback function. Actually, it is really the only practicable solution -- the only other option is coding your own extensions to the browser, and that is a little much (unless you really like banging your head against a wall). There are actually quite a few parallel questions on these boards: you might try searching for some, many are very good.

Modifying your code:

function checkEmail(email) {
    /*
        original parts of the function here!
    */

    if (email.length) {
        $.getJSON('ajax/validate', {email: email}, function(data){
            if (data == false) {
                // stuff
            }
            checkEmailResponse( data );
        })
    }
}

function checkEmailResponse( data )
{
    // do something with the data.
}
like image 140
cwallenpoole Avatar answered Oct 19 '22 22:10

cwallenpoole


You should as well use a callback because the call is asynchronous and therefore design you whole JavaScript source around that idea (as the others pointed out).

If you really really need to get it as a return value you need to turn the asynchronous call off but this is not recommended at all, because it blocks the page till the response is there.

function checkEmail(email, callback) {
    if (email.length) 
    return $.ajax({
      data:  {email: email},
      url: 'ajax/validate',
      async: false
     }).responseText; // only the raw response text of the XMLHttpRequest
    }
}
like image 32
Daff Avatar answered Oct 19 '22 22:10

Daff