Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getting progress of PHP-script

I need to provide interaction between js on html-page and php-script.
- Use AJAX.
Ok. But the problem is that php-script executing for a long time, and i need to know the state of this script processing (e.g. 60% complete)
What should i do? Create 2 php-scripts (client&server) and do ajax-request to client.php which will do requests to server.php via sockets or smth? Are there more elegant solutions?

like image 432
Dmitriy Avatar asked Sep 21 '12 19:09

Dmitriy


3 Answers

What if you had the script doing the processing write its status to a file once in awhile. Make a second script that will read the file and return the status of the original one.

like image 69
thatidiotguy Avatar answered Sep 29 '22 13:09

thatidiotguy


You should never have a long-running process being executed entirely within an HTTP session.

A simple and common approach to this problem is message queuing. Basically, you have your UI queue up the request into a database table and then have external daemon(s) process the queue.

To provide feedback, have the daemon periodically update the table with the status for the row it's currently working on. Then, your javascript code can make AJAX requests to a script that retrieves the status for that work item from the database and displays it to the user.

See: Dealing with long server-side operations using ajax?

like image 43
Justin ᚅᚔᚈᚄᚒᚔ Avatar answered Sep 29 '22 14:09

Justin ᚅᚔᚈᚄᚒᚔ


  1. Ajax call php script and return information that script is runing.
  2. Main script create lock.file.
  3. Script called from cron is checking if lock.file exists and run the correct script.
  4. The correct script saves the current progress into progress.txt.
  5. Ajax is reading progress.txt and when progress is 100% then return information that script processing is finished.

edited: Thanks to Justin for poiting the timeout problem ;)

like image 44
Norbert Orzechowicz Avatar answered Sep 29 '22 15:09

Norbert Orzechowicz