Rajasekhar
Rajasekhar

Reputation: 2455

jQuery - How to pass multiple callback functions in jQuery ajax

In JS file have multiple ajax calls,so I would like to call one AJAX call with multiple callback functions.can any one help me how to call multiple AJAX calls.Here is test code,

$.ajax({
  url : url,
  dataType : 'json',
  success : test1(data)
});

$.ajax({
  url : url,
  dataType : 'json',
  success : test2(data)
}); 

It is working fine,can you please help me how we can call both ajax calls in one.

Upvotes: 4

Views: 9586

Answers (6)

Arun P Johny
Arun P Johny

Reputation: 388436

use the promise object returned by ajax

var a1 = $.ajax({ 
    url : url, 
    dataType : 'json', 
    success : test2
})
.done(cb1)
.done(cb2);
a1.done(cb3);

Upvotes: 14

Butani Vijay
Butani Vijay

Reputation: 4239

You can use as follow :

$.ajax({
      url : url,
      dataType : 'json',
      success : function(data){
                if(url=="xyz.php")
                     test2(data);
                else if(url=="abc.php")
                     test1(data);

      } 
});

Upvotes: 3

Dennis Meissner
Dennis Meissner

Reputation: 451

You could easily define one callback function in which you would call multiple ones.

$.ajax({ 
    url: url,
    dataType: 'json', 
    success: myGlobalCallback(data) 
});

function myGlobalCallback(data) {
    cb1(data); 
    cb2(data);     
}

Upvotes: 1

iConnor
iConnor

Reputation: 20209

Like so

$.ajax({
  url : url,
  dataType : 'json',
  success : function( data ) {
     test1(data);
     test2(data);
  }
}); 

Simples.

Or to go a step further if you want all the arguments you can do this

$.ajax({
  url : url,
  dataType : 'json',
  success : function() {
     test1.apply(null, arguments);
     test2.apply(null, arguments);
  }
}); 

The you can use them like this

var test2 = function( data, status, jqXHR) {
    console.log( data, status, jqXHR );
};

Upvotes: 1

bipen
bipen

Reputation: 36551

just call both of your function inside one successs function...

 $.ajax({
   url : url,
   dataType : 'json',
   success : function(data){
      test1(data);
      test2(data);
   } 
});

Upvotes: 6

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can do this -

$.ajax({
      url : url,
      dataType : 'json',
      success : function(data){
            test2(data);
            test1(data);
      } 
});

Upvotes: 1

Related Questions