jQuery, Each() and Async Gets

H04K0067

One of the things to keep in mind when using jQuery is that nothing is a blocking call.  Sure, there is a certain sequence to when things operate.  But, to be safe, you should always assume that step two will happen during step one.

Nowhere is this more evident than when retrieving content from a URL and inserting that content in your page.

The temptation is to write code that looks something like this

 $.each(json, function(index, entry)
{
    jQuery.get(entry['url'], function(html)
    {
        // insert the HTML here.
    }
}

The problem with this is that jQuery.get is an asynchronous call.  This means that once the get has fired, the each loop will continue.  This can cause all kinds of trouble for you, including having a complete iteration skipped, or if you are doing some kind of concatenation prior to inserting the HTML, having HTML for one iteration showing up in the middle of another.

Not exactly what you had in mind, eh?

But there is a fix.  Use the ajax call instead and specify async:false to force the call to complete before allowing another call.

$.each(json, function(index, entry)
{
    jQuery.ajax({ url:  directory + '/' + entry['url'] , success: function(html)
        {
            // insert the HTML here.
        }
    }, async: false
});

Note too that using ajax without the async: false is the same as just using get.

 

Other post in jQuery

Related Post

  • jQuery – Calling Your Own FunctionsjQuery – Calling Your Own Functions While jQuery has a lot of functionality built into it, you may find that you have a need to implement your own functions and attach them to the jQuery framework in some way. There are two ways ...
  • jQuery – AccordionjQuery – Accordion If you’ve been using the MS-AJAX Accordion control, stop it right now! Seriously. Once I show you how easy the jQuery version is, you’ll want to drop it. Shoot! You may even want to go to th...
  • JQuery, Cufon, and Dynamic ContentJQuery, Cufon, and Dynamic Content Yesterday I mentioned a new tool called Cufon that allows you to easily embed fonts in your web site. One quirk about this tool is that your HTML has to be rendered prior to applying, or refres...
  • jQuery and ASP.NET UpdatePaneljQuery and ASP.NET UpdatePanel I’ve been busy over the last couple of weeks working on an administrative application that uses a ton of AJAXy stuff. The application is interactive in the sense that every time a field is update...
  • jQuery – Using Slider as a ScrollbarjQuery – Using Slider as a Scrollbar Last week I introduced the jQuery UI element known as a slider and indicated that this control could easily be used as a custom scrollbar. Today I'm going to show you exactly how that's done. ...
  • Anibal

    but $.each is an asynchronous call?

    on firefox its OK, on IE and Chrome no.

    • Dave

      I’m not sure what your point is. I never said anything about $.each being async or not (it isn’t btw). My point was that the get is async and you can use the ajax call instead to FORCE synchronous if that is what you need (which often you do not.)

  • Anibal

    I want to insert HTML in my page with the method $. append jQuery.

    $. each (ARRAYSTRING, function (index, value) {
                 $. ajax ({
                     type: “POST”
                     url: “myURL”
                     data: “{param: ‘” + value + “‘}”
                     contentType: “application / json; charset = utf-8″,
                     dataType: “json”
                     async: false,
                     success: function (data) {
                         var obj = $. parseJSON (data);
                         $ (“body”). append (obj.Html);
                     }
                 });
             });

    In Firefox HTML is inserted correctly, one by one.
    In IE and Chrome does not display the page until all elements have been loaded.

    • Dave

      The only difference is that IE and Chrome wait until the jQuery is done to render the results and FireFox renders the results as they are being added?

  • Anibal

    thanks for your reply!

  • Anibal

    I found a solution, a plugin that helps trick the browser

    http://mess.genezys.net/jquery/jquery.async.php

    p.d: this is not advertising, thanks!