0

I have read questions about multiple ajax requests, but not about the case in which I have to make 2 or more ajax requests to the same url to get different responses:

function ajaxSub(opc1, value1) {
    $.ajax({
        type: "GET",
        url: $("#urltmp1").val() + "ajax",
        async: true,
        data: {
            o: opc1,
            q: value1
        },
        datatype: "text",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8"
    })
    .done(function (msg) {
        if (opc1 == "1" && value1 == "data01") {
            $("#field01").val(msg);
        }
        if (opc1 == "1" && value1 == "data02") {
            $("#field02").val(msg);
        }
    })
    .fail(function () {
        alert("fail");
    });
}

function main01() {
    ajaxSub("1", "data01");
    ajaxSub("1", "data02");
}

This works if main01() have just one call to ajaxSub(). How can I achieve this? Thanks in advance

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 2
    Why does this not work for you? I can't see anything specifically wrong with it. – Rory McCrossan Dec 03 '14 at 14:17
  • 1
    this is because ajax is asynch. This means, when you call it first, it doesn't care what happens, immediatly call the next line of your code. – vaso123 Dec 03 '14 at 14:20
  • you could try using a setTimeout or setInterval for each function then they would execute at the same time! – www139 Dec 03 '14 at 14:23
  • What is your exact problem? Both requests should succeed, isn't that the case? – S.Pols Dec 03 '14 at 14:37
  • this only works if async:false. I have to make 10 requests to the same url because it is lots of data. – user3731337 Dec 03 '14 at 14:58
  • I will try setTimeout and setInterval – user3731337 Dec 03 '14 at 15:01
  • like @lolka_bolka said, async means it fires the code and doesnt care about right response, u can build a queue with interval/timeout or put to $.ajax async:false so it has to wait for response – UnskilledFreak Dec 03 '14 at 15:11
  • Perhaps [this answer](http://stackoverflow.com/questions/15963590/how-to-synch-javascript-callbacks/15964626#15964626) will help you. – Ja͢ck Dec 03 '14 at 23:02
  • Just for knowledge I did it using $.when(f1,f2...fn).then();. For practical purposes I did it in just one request (chunks of data delimited by a character($). Thanks guys. very interesting answer Jack. – user3731337 Dec 04 '14 at 23:32

0 Answers0