themhz
themhz

Reputation: 8424

Ajax multiple requests at the same time

recently I developed a project were I send multiple ajax requests at a single aspx page. I also put a timer were this request is happening with interval 5 seconds. Everything seems to work fine until suddenly the responses mix up. I know that I could do the same thing with one request, but I wonder why this is happening. I looked around the internet but I can't find any solution yet. I now actually adopted this style of coding like making one request with multiple results, but I wonder and I really want to know how to make multiple ajax request were the response will not mix up. This is my sample Code:

 $(document).ready(function () {
        var a = setInterval("request1()", 5000);
        var b = setInterval("request2()", 5000);
    });

function request1() {

        $.ajax({
            url: 'ajaxhandler.aspx?method=method1' ,
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=utf-8');
            },
            success: function (data) {
                  alert(data);
            }

        });
    }


function request2() {

        $.ajax({
            url: 'ajaxhandler.aspx?method=method2' ,
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=utf-8');
            },
            success: function (data) {
                  alert(data);
            }

        });
    }

Upvotes: 6

Views: 26433

Answers (4)

goertzenator
goertzenator

Reputation: 2039

The function below will accept an array of urls for JSON requests, and invoke the callback with an array of results once all requests have completed. It can be easily adapted to non-JSON use.

The idea is to stash incoming responses into an array as they arrive, and then only invoke the callback once all results are in. This approach is a nice way to batch updates to the DOM and to avoid having a timer for each node you want to update.

function multi_getJSON(urls, callback)
{
    // number of ajax requests to wait for
    var count = urls.length;

    // results of individual requests get stuffed here
    var results = [];

    // handle empty urls case
    if(count === 0)
    {
        callback(results);
        return;
    }

    urls.forEach(function(url, index)
    {
        $.getJSON(url, function(data)
        {
            results[index] = data;
            count = count - 1;

            // are we finished?
            if(count === 0)
            {
                callback(results);
            }
        });
    });
}

Upvotes: 2

Jon Newmuis
Jon Newmuis

Reputation: 26492

As has been stated, you cannot guarantee the order that the results return in. But if it is necessary to be able to determine this, you could conceivably create a unique identifier for each asynchronous request that is made, then sort out the incoming responses accordingly.

An example where I see such a solution being useful is when performing actions on keystroke (e.g. onkeyup). When doing something like this, you may wish to encode a timestamp, version number, or similar, so that you can guarantee some sort of order. If the user is attempting to search "test", it is possible that the autocomplete response for "tes" would be returned before the response for "te". If you simply overwrite the autocomplete data, then this will obviously not be the desired behavior, as you could display incorrect results for the current search token(s).

Encoding a timestamp (or unique ID, counter, version number, key, etc.) will allow you to check this to verify that you have the most up-to-date response, or sort the results by timestamp if you need to guarantee order, etc.

Upvotes: 2

Mohsen
Mohsen

Reputation: 65785

This is not JavaScript fault, it's messed up because you are calling a single page in same time. If you had two server side page for your two AJAX files then it would be fine. Try to create two different aspx file for you different methods to have them called together.

But that would not be a good practice. Why don't sent the method as an parameter and have a condition in your aspx file for different methods? Then if you have two (or more) methods used at the same time, then simply send both to server with an single call. You will save a HTTP header and call delay for your call.

function requestAll() {

        $.ajax({
            url: 'ajaxhandler.aspx' ,
            data: ['method1', 'method2'],
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=utf-8');
            },
            success: function (data) {
                  alert(data);
            }

        });
    }

Upvotes: 2

calvinf
calvinf

Reputation: 3914

If you need the requests to happen in order, you shouldn't be using AJAX (the first "a" is for "asynchronous").

To address this you can call request2() in the callback for the "success" of your first request.

function request1() {
    $.ajax({
        url: 'ajaxhandler.aspx?method=method1' ,
        beforeSend: function (xhr) {
            xhr.overrideMimeType('text/plain; charset=utf-8');
        },
        success: function (data) {
              request2();
        }

    });
}

Upvotes: 7

Related Questions