0

i have 2 ajax requests in 1 page. i want to run that 2 ajax requests together at same time.

First AJAX

$.ajax({
    url: "load1.php",
    type: 'POST',
    success: function (output) {
        console.log(output);
    }
});

Second AJAX

$.ajax({
    url: "load2.php",
    type: 'POST',
    success: function (output) {
        console.log(output);
    }
});

on load1.php i add sleep(10); code, so it will delay 10 seconds.

so while i tried to sleep the first ajax request, the second ajax will wait 10 seconds for the first ajax until its done. i know it can be done by using async:false. but i don't want to use it. is there another way to prevent it and let the second ajax load without waiting the first ajax?

Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
Willyanto Halim
  • 413
  • 1
  • 6
  • 19

2 Answers2

0

In that case, sleep will not fulfill your requirements. Sleep will delay all of these execution. You can use setTimeout/setInterval for your first ajax request. Then your 2nd ajax request will execute independently & first one will execute after 10 seconds.

Something like this

 setTimeout(function(){ 
    $.ajax({
    url: "load1.php",
    type: 'POST',
    success: function (output) {
     console.log(output);
    }
  });

  }, 10000);
Jobayer
  • 1,221
  • 1
  • 14
  • 22
  • if the connection to mysql is denied or the server is down. it's better to use sleep. because it's the same condition. – Willyanto Halim Mar 03 '18 at 04:41
  • by the way, i don't questioned about sleep or settimeout. – Willyanto Halim Mar 03 '18 at 04:42
  • Issue is - sleep will delay all existing code execution(check http://php.net/manual/en/function.sleep.php) – Jobayer Mar 03 '18 at 04:43
  • so how about if the connection is down? i want the second one can response without the first ajax done.. it's a same case. – Willyanto Halim Mar 03 '18 at 04:46
  • have you tested it using setTimeout? in that case, 2nd one will send response before first one. Because you are delaying first ajax call for certain time. Use this approach & check your browser's network tab, hope it will be clear to you. – Jobayer Mar 03 '18 at 04:50
0

from @G_S statement. it was true that ajax is asynchronous by default. when we use async:false then ajax will become synchronous. i have found my problem that in my php files there was session_start in every files. then when I put sleep code in one of files, it will become session lock. it means that the ajax will wait the session start again to load if there were sleep code..

Willyanto Halim
  • 413
  • 1
  • 6
  • 19