views:

54

answers:

2

I have a situation where I need to make sequential AJAX requests represented by an ordered list (<ol><li>..) on the page. I use jQuery.

Requirements:

  1. Each request has to wait for the previous one to complete with a successful status.
  2. The success or error message needs to be appended to the corresponding list item.
  3. The process should halt if an error occurs on any item.
  4. Errors may be HTTP errors or an error returned with the JSON formatted response.

What I have working:

  1. Looping over list
  2. Making $.getJSON call to the desired URL for each list item

The 'Requirements' items are the pieces I haven't worked out.


SOLUTION

I ended up using jQuery Message Queuing, but I didn't find a way to return HTTP errors to the item that spawned the request. I instead display an error in a different place.

$(document).ajaxError(function(event, response, settings, exception){
    $('#Admin').append('<p class="error">' + response.status + ' error requesting page:<br />' + settings.url + '<br />Reload this page to continue.</p>');
});

I would prefer to display HTTP errors with the item if anyone can help me with that.

+1  A: 

jQuery Message Queuing is what you might be looking for. It performs serial (sequential) AJAX requests.

You can view a demo here.

Vivin Paliath
Looks promising! Checking it out now.
Sonny
+1  A: 

There can be possibly two ways:-

  • Use of jQuery.ajaxQueue Plugin. This plugin will help you manage the "Ajax race conditions".
  • Use of Synchronous call to jQuery.ajax (click the "options" tab to see them). To make the call synchronous, you'll set the "async" option in the Ajax call to false. But, it'll slow things down.

Hope it helps.

Knowledge Craving