2

In my Javascript file I have multiple ajax calls, I would like to change all ajax calls to one ajax call. Here is my sample JS code.

var vpnPin = $.ajax({ 
  dataType: "json",
  url: "url",
  async: true,
  success: function(result) {}                     
});  //$.ajax() ends


var vpnDataPlan = $.ajax({ 
  dataType: "json",
  url: "url",
  async: true,
  success: function(result) {}  
});  //$.ajax() ends

How can we call multiple AJAX calls to one AJAX call?

Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216
Rajasekhar
  • 2,215
  • 3
  • 23
  • 38

2 Answers2

7

It is possible using promises concept in javascript. Read promises and defered.

Using your above example it can be done like:

//assuming vpnPin and vpnDataPlan are the deferred object returned from $.ajax.
//As you have done in your example.

$.when(vpnPin, vpnDataPlan).done(function(){
    //work to do after the completion of both calls.
});

There are many more variations of this. RSVP implements the standard way of handling promises.

guleria
  • 741
  • 2
  • 11
  • 23
3

Not possible in most cases

Each ajax call involves the browser sending information to a server at a particular URL.

If you reduced the browser code from two ajax calls to one ajax call, the server would receive less information, the browser would not receive some information it is getting now, and/or the server would perform fewer operations.

If you control the server code, you might be able to change the server code to be able to do both operations in one step. Only then could you change the browser code.

Paul
  • 26,170
  • 12
  • 85
  • 119