Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax request are not async

Tags:

ajax

I have an ajax problem:

foreach(ids as id){
  $.ajax({
    url:'script.php',
    data:'id='+id,
    cache:false,
  });
}

If I loop 6 times (in my foreach loop) I should have 6 asynchronous requests being made to the server. But the ajax calls in this case are called synchronously, and not asynchronously. Any one have any idea why this happens?

like image 328
albanx Avatar asked Dec 16 '22 17:12

albanx


1 Answers

Ok thanks. After some hours of analysing and reflecting I realized why this script goes syncronsly: I open the script.php file and I notice this and the beginig of the file:

<?php
session_start();
$var1=$_SESSION['SOMEVAR'];
.......
//do php script.....

.......
?>

So I have parallel ajax calls to a php script that uses session, but sessions in this case locks the calls to be executed syncrosnly cause of the session vars request, so the solution of this problem is:

<?php
session_start();
$var1=$_SESSION['SOMEVAR'];
//get all session var
......
session_write_close();//then close it
.......
//do php script.....

.......
?>

With session_write_close i have my script to make the ajax calls in async way. a good explain here http://konrness.com/php5/how-to-prevent-blocking-php-requests/

like image 133
albanx Avatar answered Jan 03 '23 06:01

albanx