Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Can I send and receive an $.ajax response while a longer $.ajax request is pending?

Situation:
I'm using an $.ajax() POST to send a request to a php script that inserts about 400,000-500,000 lines into a db. This consistently takes about 3.5 - 4 minutes. (During this time, the request is PENDING).

Problem:
I need some way to show progress on the page. (such as a %). I tried using an $.ajax() in a setInterval that checks every 5 seconds or so, but they seem to build up and all come through when the first (longer) $.ajax() is finished.

Question:
Isn't $.ajax() async by default? Shouldn't this mean requests can be sent out in any order and at any time, and responses should be received in any order and at any time?? Does this even have anything to do with async? Is there a way to periodically send back 'semi-responses' from one request? Or can't I send and receive requests/responses while there is a pending request/response? (see awesome drawing below)

Thanks in advance!!!

multiple requests http://kshaneb.com/reqres.png

like image 990
ksb86 Avatar asked Jun 21 '13 06:06

ksb86


1 Answers

Your long-running ajax-call probably opens a session on server, so all next requests are blocked due to a session file lock.

Problem: PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing. The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.

Solution: The session file remains locked until the script completes or the session is manually closed. To prevent multiple PHP requests (that need $_SESSION data) from blocking, you can start the session and then close the session. This will unlock the session file and allow the remaining requests to continue running, even before the initial request has completed.

More info here: http://konrness.com/php5/how-to-prevent-blocking-php-requests/

like image 62
optimistiks Avatar answered Oct 20 '22 11:10

optimistiks