Sack
Sack

Reputation: 1

JQuery load() inside for loop

I'm trying to write a Greasemonkey script where different pages are loaded with .load() using a for loop and store some of their informations in localStorage. My Problem: because .load() is asynchronous it doesn't work well. My script just stores the Last value I am trying to store. I think that is because i use the var i inside the callback function, and when the callback function is fired i has already another value.

for (var i = 0; i < plantsDiv.length; i++)
{
   objectid = plantsDiv[i].getAttribute('objectid');    
   $("#wrap").load("index.php?objectid="+ objectid,function(){
      //[...] what is happening
      window.localStorage.setItem(objectid,value);
   });
}

When i insert alert("foo") between the callback function and the end of the for loop everything works, because the .load function is loaded, while i am clicking "ok" in the alert window. Is there any way to let the for loop wait until the whole .load is executed?

Thanks for your help, and sorry for my Bad english :)

Upvotes: 0

Views: 1623

Answers (2)

cernunnos
cernunnos

Reputation: 2806

If the objective is not loading the content into an element and instead is to get the content and save it into localStorage you should user $.get (or $.post if you want to post data).

jQuery ajax functions return a jqXHR object, which is derived from a Deferred object, so you can use .done() for success and .fail() for failure:

$.get("index.php?objectid="+ objectid)
.done(function(data) {
    window.localStorage.setItem(objectid,data);
})
.fail(function() {
    // try again later?
});

Edit: Note that the requests will still be launched asynchronously and in this case you may have a lot of parallel requests, the code in the done (or fail) blocks will be run when the response of each request is received.

Upvotes: 0

Lix
Lix

Reputation: 47976

The load() function is pretty much the same as a get() function -

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function.

By using the slightly more verbose ajax() function, you'll be able to specify the request to be synchronous with async set to false. Perhaps this will solve your issue.

A simple, synchronous ajax call :

$.ajax({
  url: "example.php",
  data : yourData,
  async : false
},function(response){
  // this is the callback
});

References -

Upvotes: 1

Related Questions