Home » jQuery » jQuery, Each() and Async Gets

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 – EventsjQuery – Events As well as being able to change the class associated with an element or a set of elements on a screen, jQuery also allows you to fire events.  You might want to do this, for example, if […]
  • 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 […]
  • jQuery, JSON, and ASP.NETjQuery, JSON, and ASP.NET A few months ago, I demonstrated how to use ASP.NET's JSON capabilities.  Lately, I've been demonstrating how to use jQuery.  Both use a considerable amount of JavaScript so if there is […]
  • jQuery SplitterjQuery Splitter Hey!  This is pretty cool. I was just mentioning at the last jQuery presentation I did that there were some controls that were definitely missing from the jQuery UI suite of […]
  • jQuery ProgressbarjQuery Progressbar Once you venture into the land of AJAX you’ll soon discover the need to let your user know that some work is taking place in the background.  If you can, you’ll want to let them know […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS.Does your team need additional help in any of the above? Contact Dave today.

  • 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!