0
votes

I have the following code which loads via ajax contents to be appended:

    $.get('http://mydomain.com/ajax1.php/', function(data){
        var data_one = $(data).find('#ajax_editor_suggestion_container');
        $('.ajax_editor_selection_container').append(data_one);
    }); 

    $.get('http://mydomain.com/ajax2.php/', function(data){
        var data_one = $(data).find('#ajax_editor_suggestion_container');
        $('.ajax_editor_selection_container').append(data_one);
    }); 

My objective is to have the contents of ajax1.php appended first and then contents of ajax2.php appended after that. However sometimes the contents of ajax2.php gets loaded before that of ajax1.php and messes up the appended order.

So my question is, how do I ensure that the contents of ajax2.php are always appended after the contents of ajax1.php?

I'm using $.get() because it's easier for me but I'm open to any other jQuery ajax methods.

Thanks

1
or use prepend() on the first one...epascarello

1 Answers

1
votes

I would use $.when:

$.when(
    $.get('http://mydomain.com/ajax1.php/'), 
    $.get('http://mydomain.com/ajax2.php/')
).done(function (response1, response2) {
    var data_one = $(response1).find('#ajax_editor_suggestion_container');
    var data_two = $(response2).find('#ajax_editor_suggestion_container');

    $('.ajax_editor_selection_container').append(data_one).append(data_two);
});

That will run the ajax requests at the same time, but won't call the callback until both have finished.