0

I'm pulling content from a series of pages using .get() and want to append the pulled content in the order in which each page appears in an array I set. However, the aggregated page is appending items as soon as they're ready instead. How can I dictate the order in which items are appended?

function loadHTML() {
    for(i = 0; i < 4; i++) {                        
        var slug = ["slug-1", "slug-2", "slug-3", "slug-4"]
        $.get('http://website.com/' + slug[i], function(data) { 
            var text = $(data).find(".text").html();
            var title = $(data).find("#title").html();
            $("#page").append("<div class='content_block'><h1>" + title + "</h1>" + text + "</div>");
        });
    }
};  

loadHTML();
jean-max
  • 1,640
  • 1
  • 18
  • 33
westcoast_509
  • 322
  • 1
  • 4
  • 13
  • http://stackoverflow.com/questions/2687679/jquery-ajax-inside-a-loop-problem – mplungjan Jan 25 '17 at 16:07
  • 2
    how about a recursive call? So that when the first is loaded, the second gets called? The problem with asynchronous javascript is you have no control over when they retrieve. – Snowmonkey Jan 25 '17 at 16:07
  • In general making multiple get requests in a loop is not a good idea. Updating the receiving action on the server to be able to take in an array of values and process them, sending back multiple results in one call might be better if possible. What if one of the calls fails, or worse, hangs but you depend on all of them to come back successfully? – Nope Jan 25 '17 at 16:09
  • 1
    You could hold the contents in memory instead of appending them directly after they are fetched. Just create a var like "$("
    ")" for holding content and put the vars in an array or json structure. And "oncomplete" for the last page you could append the contents in the desired order, maybe you're just messing a bit with javascript sorting. (And you definititely should avoid turning async off, which would be bad practice)
    – Gunnar Jan 25 '17 at 16:13

1 Answers1

3

You need to use the callback to call again:

var cnt = 0;
var slug = ["slug-1", "slug-2", "slug-3", "slug-4"];
function loadHTML() {
  if (cnt>=slug.length) return; // stop
  $.get('http://website.com/' + slug[cnt++], function(data) { 
    var text = $(data).find(".text").html();
    var title = $(data).find("#title").html();
    $("#page").append("<div class='content_block'><h1>" + title + "</h1>" + text + "</div>");
    loadHTML();
  });
}
loadHTML();

OR have one server process take the array and return the data in one chunk

mplungjan
  • 169,008
  • 28
  • 173
  • 236