0

I need to call a particular PHP script on my server several times. As each call will take some time (e.g. about .5 seconds) and each call is independent of each other, I want to call the scripts concurrently. Right now, I have something like this:

$(document).ready(function() {

    $.ajax({
      url: 'main.php',
      method: 'POST',
      data: { foo: 'foo' },
      success: function(result) {
        console.log(result);
      }
    });

    $.ajax({
      url: 'main.php',
      method: 'POST',
      data: { bar: 'bar' },
      success: function(result) {
        console.log(result);
      }
    });

});

Instead of making these calls sequentially, I want to do them concurrently. How do I do that?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
StackOverflowNewbie
  • 39,403
  • 111
  • 277
  • 441
  • 1
    What is not concurrent with what you have shown ? There is no way to achieve two independent calls beside the one you're using. – elad.chen Aug 24 '15 at 19:06
  • These will be called at the same time as it is right now – tymeJV Aug 24 '15 at 19:06
  • 1
    ajax is asynchronous! Look at your network in dev tools , will see they are concurrent – charlietfl Aug 24 '15 at 19:07
  • 1
    Javascript only has one thread. As long as you don't have global ajax settings causing the requests to be synchronous, that's about as concurrent as it gets. – Stryner Aug 24 '15 at 19:07

3 Answers3

1

Not sure what issue you are experiencing but you are making concurrent AJAX calls because jQuery defaults to async: true. If it defaulted to false then it would be called SJAX lol

One issue which you might be experiencing would be a session handling lockup.

If main.php is using session_start() then it will simply queue the bar request until foo finishes. Or you can manually call session_write_close() to avoid the lockup.

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

Set your async = true on your AJAX calls to make them asynchronous.

$.ajax({
    async: "true",
      url: 'main.php',
      method: 'POST',
      data: { foo: 'foo' },
      success: function(result) {
        console.log(result);
      }
    });

    $.ajax({
    async: "true",
      url: 'main.php',
      method: 'POST',
      data: { bar: 'bar' },
      success: function(result) {
        console.log(result);
      }
    });
Bryant Frankford
  • 401
  • 3
  • 14
0

Ajax requests are asynchronous by nature. Based on your example, each of the calls will be dispatched without waiting for the server's response

elad.chen
  • 2,375
  • 5
  • 25
  • 37