views:

116

answers:

3

I'm currently creating an update script, whereby I have a list of tasks each detailed in a UL, example below:

<ul id="tasks"><li id="task1">Task one</li><li id="task2">Task two</li><li id="task3">Task three</li></ul>

I'm looking for a way for jQuery to systematically loop through each li and perform an AJAX request for each specific ID. More specifically, I'd like to do this automatically (without user interaction) performing each individual request in order... e.g when li#1 is finished, it'll start on the next.

I can loop through each li by using the following, but I can't see to get the AJAX to automatically perform its request

$('li').each(function(index) { task = $(this).attr('id'); /* perform the task */ });

Can anyone help?

A: 
$('li').each(function(index) {\

$.post("test.php", { name: "John", time: "2pm" },
   function(data){
     alert("Data Loaded: " + data);
   });

  });

i call jquery ajax function inside jquery function. I hope this should work.

http://api.jquery.com/jQuery.post/

zod
A: 

If you are wanting to perform an AJAX action on a number of elements in the page simultaneously, you are far better compiling them all together, doing a single AJAX interaction with the server, and then parsing the response. Otherwise, if you have a list with 100 items, you will be doing 100 round trips to the server - anything but efficient.

So, taking @zod's code as a base:

var idArray = array();

$('li').each(function(){
  idArray.push( $(this).attr('id') );
});

$.post(
  "test.php" ,
  {
    ids: idArray.join(',') ,
    anything: "else"
  } ,
  function(data){
    alert("Data Loaded: " + data);
  });
});

Within your PHP (or other server-side language) script, you simply split the ids variable into the individual values, process them each, and then concatenate the completed response (maybe in using JSON) and then ensure that the function in the $.post() parses the data out as required.

Lucanos
A: 

You could write a function that loops until it runs out of <li> elements, going to the .next() on AJAX success, like this:

function execTask(li) {
  if(!li.length) return; //no more left, abort out
  $.ajax({ 
    url: "something",
    data: { task: li.attr("id") },
    success: function() { execNextTask(li.next()); }
  });
}

Then on load or whenever you want to kick it off, just call it on the first <li>, like this:

execTask($('#tasks li:first'));
Nick Craver