How can I return an AJAX-retrieved value to the parent function of the current function in JavaScript?
ajax, javascript, jquery
Solution
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.
}
Problem
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!