How do I return the response from an asynchronous call?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
1 like 0 dislike
53 views

I have a function foo which makes an Ajax request. How can I return the response from foo?

I tried returning the value from the success callback, as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response.

by (230 points) | 53 views

1 Answer

0 like 0 dislike

The A in Ajax stands for asynchronous . That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.

Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer:

Synchronous

Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer that you needed.

by (1.2k points)

Related questions

110,608 questions
257,186 answers
0 comments
28,158 users