How to return the AJAX return value of the parent function of the current function in JavaScript?

I have the following JavaScript code (and jQuery):

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 be return data for the parent function, checkEmail() . I tried to do 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 will not work, because the call to $.getJSON() is asynchronous, so it will return ret until the GET request completes.

Any thoughts here?

Thanks!

+6
javascript jquery ajax
source share
4 answers

Generally, the best way to deal with this type of problem is to use some form of callback function. In fact, this is really the only possible solution - the only option is to encode your own extensions in the browser, and thatโ€™s a bit (if you donโ€™t like to bang your head against the wall). There are quite a few parallel questions on these boards: you can try to find someone, many of them are very good.

Code change:

 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. } 
+9
source share

You should also use a callback because the call is asynchronous and therefore creates the whole JavaScript source for you around this idea (as others have pointed out).

If you really need to get it as a return value, you need to disable the asynchronous call, but this is not recommended at all, because it blocks the page until an answer appears.

 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 } } 
+2
source share

You can have a parent function block until something appears there. And to reduce processor intensity, you can use somekind timeout.

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

}

Hope this helps.

0
source share

You just need to change the way you solve the problem. You know that what you have above will not work, so you cannot think of the terms โ€œcall a function and work with its return valueโ€.

You need to switch to something like a CPS offer or depending on the launch of this function, processing it with custom events.

0
source share

All Articles