HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Multiple url in same ajax call?is this possible?

Can I send my data to multiple pages using ajax call? I dont want to use another ajax call for this.

Sample code:

 $.ajax({
     type: 'POST',
     url: '../services/form_data.php', //can I send data to multiple url with same ajax call.
     data: {
         answer_service: answer,
         expertise_service: expertise,
         email_service: email,
     },
     success: function (data) {
         $(".error_msg").text(data);
     }
 });

Upvotes: 15

Views: 57823

Answers (4)

Joaquin Lopez
Joaquin Lopez

Reputation: 11

Using '$.when' could be an alternative as well. I have used it in one of my project.

Reading jQuery API instructions:

Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
  .then( myFunc, myFailure );

Upvotes: 1

Paul
Paul

Reputation: 27423

All you need is $.each and the two parameter form of $.ajax

var urls = ['/url/one','/url/two', ....];

$.each(urls, function(i,u){ 
     $.ajax(u, 
       { type: 'POST',
         data: {
            answer_service: answer,
            expertise_service: expertise,
            email_service: email,
         },
         success: function (data) {
             $(".error_msg").text(data);
         } 
       }
     );
});

Note: The messages generated by the success callback will overwrite each other as shown. You'll probably want to use $('#someDiv').append() or similar in the success function.

Upvotes: 16

Or Duan
Or Duan

Reputation: 13810

You can't use the same code for 1 request from many pages.

BUT you can send 2 requests. its can be done by copy paste your ajax code or by build a function that gets URL and send request with this URL

function sendMyAjax(URL_address){
    $.ajax({
         type: 'POST',
         url: URL_address,
         data: {
             answer_service: answer,
             expertise_service: expertise,
             email_service: email,
         },
         success: function (data) {
             $(".error_msg").text(data);
         }
     });
};

Upvotes: 18

RichieHindle
RichieHindle

Reputation: 281405

A single AJAX request can only talk to one URL, but you can create multiple AJAX requests for different URLs, and they will do their work simultaneously - you wouldn't need to wait for one to complete before firing off the next one.

(If your URLs are on the same server, you could consider refactoring your server-side code so that a single URL does all the work that your multiple URLs do now.)

Upvotes: 4

Related Questions