Flatline1963
Flatline1963

Reputation: 147

Multiple jQuery ajax calls; how can associate callbacks to requests?

If you are dynamically creating ajax requests, since they come to execute the success callback asychronously, how can you know what request is being responded by each callback ?

Example:

I have an array of n Questions, and a server gives back the Answers:

var questions = Array("What's your name?", "What's your mom's name?", "What's your pet's name?");
for (var i=0; i<questions.length; i++) {
            $.get ("server.php", { "Question" : questions[i] },
                    function(data) { 
                        /* I want to process answer, but at this time I cannot access the value of i,
                           so what's question is being answered ? */
                    }, "json");
}

Upvotes: 1

Views: 86

Answers (1)

maqjav
maqjav

Reputation: 2434

Try with the next:

$.get("server.php", { "Question" : questions[i] },
    function(data) {
        alert("success. The next question is being answered: "+questions[i]);
    }, "json")
    .done(function() { alert("second succes. This question has been answered:" + questions[i]); })
    .fail(function() { alert("Error answering this question: "  +questions[i]); })

You can send in the response what question is being answered too, so you have that information in the data variable.

Working test:

var questions = Array("What's your name?", "What's your mom's name?", "What's your pet's name?");
for (var i=0; i<questions.length; i++) {
   sendGet(questions[i]);
}

function sendGet(question) {
    $.get("server.php", { "Question" : question },
    function(data) {
        alert("success. The next question is being answered: "+question);
    }, "json")
    .done(function() { alert("second succes. This question has been answered:" + question); })
    .fail(function() { alert("Error answering this question: "  +question); })
}

Upvotes: 1

Related Questions