I tried to use ajax requests and response async, but it seems not to work. I'm sending every second ajax request. The console should print out "DON'T WAIT" every second and "WAIT5" every 5 Seconds (sleep in php). But what happens is, that "DON'T WAIT" get logged, then the whole site/script waits 5 Seconds and both messages are logged 5 times. How can I make this async, so "DON'T WAIT" comes really every second and doesn't wait for the other script ?
//Edit: This is an example. The idea is later to Execute a code ( not setInterval ) which need 10 seconds to get the done-status. In this time the other setInterval should work as normal and not waiting ! The sleep as sleep(rand(5,10));
Javascript:
function getProductionStatus() {
jQuery.ajax({
url: "report.sessioncall.php",
dataType: "json",
async: true
})
.done(function(data) {
console.log(data);
});
}
function getProductionStatusLong() {
jQuery.ajax({
url: "report.sessioncall1.php",
dataType: "json",
async: true
})
.done(function(data) {
console.log(data);
});
}
window.setInterval(getProductionStatus, 1000);
window.setInterval(getProductionStatusLong, 1000);
PHP:
<?php
session_start();
sleep(5);
$_SESSION["jobs"] = "WAIT5";
$sessionstatus = json_encode($_SESSION["jobs"]);
echo $sessionstatus ;
?>
AND
<?php
session_start();
$_SESSION["jobs"] = "DONT WAIT";
$sessionstatus = json_encode($_SESSION["jobs"]);
echo $sessionstatus ;
?>
Ajax requests are asynchronous by default. If you don't change this by using $.ajaxSetup({async:false}), there is no need to write async: true in your ajax request.
The reason for this is, that in the most cases, it's bad practice to make synchronous ajax request, because you can worsen your user experience by preventing your browser to react on user input.
Just change
window.setInterval(getProductionStatusLong, 1000);
to
window.setInterval(getProductionStatusLong, 5000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With