Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make two ajax request in one hit in JavaScript or jQuery?

Can I make two or multiple Ajax requests in one hit in JavaScript or jQuery?

I mean I know it seems crazy to ask this question, but earlier I have been through an interview and they asked me this question. After the interview I searched a lot on this but found nothing.

Somewhere I just found that you can put another Ajax request as the callback of first one. But this is not the real story at all.

I have a doubt, does sync or async has some role in this?

If somebody has a solution, a POC on jsfiddle or plunkr will be appreciated on the same.

JavaScript experts, please help. Thanks in Advance!!

like image 554
Ashish Kumar Avatar asked Jan 03 '14 15:01

Ashish Kumar


1 Answers

If you are using jQuery you can make use of the deferred objects. Basically you can perform multiple ajax requests, and when all are done, one callback is executed.

Have a look at http://api.jquery.com/jquery.when/ for more information. There's also a simple example:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )   
    .then( myFunc, myFailure );
like image 85
T. Junghans Avatar answered Sep 21 '22 16:09

T. Junghans