4

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.

1
  • success : test1(data) and success : test2(data) cannot 'working fine' ! Commented Jul 29, 2013 at 11:00

6 Answers 6

14

use the promise object returned by ajax

var a1 = $.ajax({ 
    url : url, 
    dataType : 'json', 
    success : test2
})
.done(cb1)
.done(cb2);
a1.done(cb3);
Sign up to request clarification or add additional context in comments.

2 Comments

this is actually the best answer.
What happens when cb1 throws an exception?
6

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

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

Comments

3

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);

      } 
});

Comments

1

You can do this -

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

Comments

1

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 );
};

Comments

1

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);     
}

1 Comment

You are not waiting the success event to happen to call myGlobalCallback function, and BTW, when success is fired, you use returned function value, if any which is not the case here. In fact, as data is undefined, this will bring an error. You want: success: myGlobalCallback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.