AJAX runs ASYNCHRONOUSLY by default
Your AJAX functions run asynchronously, so they don't interrupt the flow of your JavaScript code. What this means is that they send a request, then wait for a response and process whatever you put in your success
function. All the while, the rest of the code keeps running.
Your best option is probably to take whatever you're doing with the AJAX return out of the for
loop and pass it into the success
parameter of your AJAX query, like this:
$.getJSON("getAnswers?question_id="+questionId,function(data){
... handle data, parse it, write to page etc ...
});
You can make AJAX run in a synchronous manner with a different call syntax, but even from here you'll struggle to get a return
out of it:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success,
async: false
});
Without knowing more about your code and what you're doing with the return, I can't say for certain how you should approach this, but 99 times out of 100 running an AJAX request in the way you're doing it is poor software engineering.