How Do "recursive Ajax Callbacks" In Javascript Work?
Solution 1:
Ajax calls are usually asynchronous. That means that when you make the ajax call, it just initiates the ajax call and it finishes some time later. Meanwhile, the rest of your code after the initiation of the ajax call keeps running until completion.
Then, sometime later when the ajax call finishes, the success function is called and, in your case, the callback function gets called by the success function. It is important to understand that the success function is called much later after the makeAJAXCall()
function has already finished.
Thus, you cannot return the ajax data from the makeAJAXCall()
function because it isn't known yet when that function returns.
In fact, the only two places you can use the results of the ajax call are:
- In the success handler directly
- In some function that the success handler calls which in your case it the callback function.
So, it is doing you no good to return returnedJSON.data.content;
from the callback function. That is just returning into some internal part of the ajax infrastructure and doing nothing. That return value will just be dropped on the floor and lost.
Instead, you need to put whatever code wants to use returnedJSON.data.content
right there in that callback function (or pass it to another function with a function call).
Ajax is asynchronous. That means you can't do normal sequential programming when using ajax. Instead, you have to do event driven programming where the event in this case is the callback that is called upon a success completion of the ajax call. All work that uses those ajax results needs to commence from that success handler or the callback that is called from it.
Post a Comment for "How Do "recursive Ajax Callbacks" In Javascript Work?"