0

I have the following code that is supposed to display 3 products when the page loads:

for(i=0;i<3;i++) {
    document.forms['search_info'].elements['page'].value = i+',1,'+(i+1);
    var jsonData = $('#search_info').serializeArray();
    var page = document.forms['search_info'].elements['page'].value.split(',');
    var limitData = {'name':'limit','value': page[0]+','+page[1]};
    jsonData.push(viewData);
    jsonData.push(limitData);
    $.ajax({
        type: "GET",
        dataType: "json",
        url: 'index.php',
        cache: false,
        data: jsonData,

        success: function(data) {
            var text = data.output;
            var el = $('#scroller');
            el.append('<li>' + text + '</li>').hide().fadeIn(450);
        }
    });
}

and it actually does the job, the only problem is the order of products; every time I reload the page the items appear in a random order.

Any idea why this is happening? How can I fix this issue?

user2428118
  • 7,935
  • 4
  • 45
  • 72
Tohid
  • 21,535
  • 8
  • 30
  • 43
  • Possible duplicate: http://stackoverflow.com/questions/6295305/php-jquery-ajax-calls-out-of-order/6295450#6295450 – aorcsik Nov 24 '11 at 16:34

2 Answers2

1

The calls are happening a-synchronous, and are started practically at the same time. The order of completion can differ every time.

By adding the async: false to your code it should work:

       $.ajax({
            type: "GET",
            dataType: "json",
            url: 'index.php',
            cache: false,
            data: jsonData,
            async: false

Also look at the documentation about it here: http://api.jquery.com/jQuery.ajax/

Rene Pot
  • 24,681
  • 7
  • 68
  • 92
1

That's because AJAX calls are asynchronous. While you're firing them off in sequential order, the actual order of completion depends ENTIRELY on other factors: how fast the remote server responds, how fast each individual HTTP connection works, etc...

If you need to guarantee the order that the responses are displayed in, you'll have to embed ordering information in the response to say that "this piece of data is for Request #0" or "... Request #2", etc... and then use that extra bit of information to make sure you inject the response data in the proper spot.

Marc B
  • 356,200
  • 43
  • 426
  • 500