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

Answers:

Answer

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

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.

Answer

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.