Reputation: 191
I'm trying to have a "loading message" of sorts letting me know where a PHP script is at during the execution process; in order to do this, I am attempting to echo HTML/javascript markup throughout the process, but none of the echos are executing until after the rest of the script has run. Is there any way around this other than using AJAX, or is it simply the nature of the beast?
Upvotes: 1
Views: 156
Reputation: 36015
You can use flush
or ob_flush
(after first having started with ob_start
) - however different browsers will handle early content sent to them in different ways. One rule that always used to be true (I haven't checked recently) was that most browsers wouldn't start rendering anything until they had received a certain number of bytes.
Now, as you know, there are better ways to do this. Ajax is probably the best. However I have used this system in a number of backend admin scripts, which has worked fine. Basically, first off do the following:
ob_start();
echo strpad('', 1024, ' ');
ob_flush();
echo '<script>updateProgress(0.1);</script>';ob_flush();
/// do something else
echo '<script>updateProgress(0.2);</script>';ob_flush();
/// do something else...
echo '<script>updateProgress(0.3);</script>';ob_flush();
Upvotes: 0
Reputation: 3362
I'd suggest doing both requests with AJAX. First request will work until the job is done. Second request will repeat itself every few seconds, pulling data from database and echoing the progress in JSON, which is then parsed by JavaScript and the progress is updated. You could even do some sort of a progress bar on top of that!
Upvotes: 0
Reputation: 1087
Ajax sounds like the way to go. Start the big operation using one request, and poll regularly using another.
One thing worth noting though, if you're using sessions: PHP's default session handler blocks on session_start, so you can not handle two requests for the same session. The second will wait until the session is closed in the first. If your polling is not returning a response until after your big operation has finished, you'll have to work around this.
If the operation is really big, consider running it in the background rather than during the request. You could just have a progress page refresh every second or so. Not very elegant, but probably much easier to implement.
Upvotes: 1
Reputation: 3710
You could have the script request another file from your server, and pass information in GET. But I wouldn't recommend this to anyone. It's essentially useless for anything other then debugging.
This would not even be accomplished using ajax because php is wholly executed on the server. Ajax requests are executed from the user's browser.
Another method to accomplish this would be to make sql inserts as you go along.
Edit: If you want this information in real time. It's not going to be easy to accomplish. You would need to mix what I posted above, with ajax to request the information in another page.
Upvotes: 0