Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two AJAX function calls - Best practice

Tags:

jquery

ajax

I need the results of two AJAX calls, after which I will use the information retrieved to create a table.

I was curious... is nesting oneAJAX call within the other and keeping the code for creating the table at the end of the 2nd AJAX call the proper way to achieve this?

Thank you for your help.


1 Answers

I'd suggest using jQuery's deferreds for this.

$ajax1 = $.ajax({
    url: '/page1'
});

$ajax2 = $.ajax({
    url: '/page2'
});

$.when($ajax1, $ajax2).done(function(data1, data2){
    // data1[0] is the result of the 1st AJAX call,
    // and data2[0] is the result of the 2nd
    // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
});

Both AJAX calls will be fired and .done will only run once both are finished.

Docs for $.when: http://api.jquery.com/jQuery.when/

like image 52
Rocket Hazmat Avatar answered Jun 03 '26 06:06

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!