Reputation: 92
I have a really big php script that can be called from jquery using $.post or ajax. Now since this script is quiet long I have divided it into several parts, so what I want is when certain part of the script is complete I want to echo a flag and then on jquery should read that flag value and accordingly display a comment. So basically I want a loader that responds in real time.
For example lets say I have three segments in php, one that does validation and one that saves the data into the database and finally one that creates a file and keeps log in it. Now remember either all these segments should execute one after the other or none should occur hence it is a single call. So what I want to create is a loader that will notify the user when each segment finishes. Something like the following
<?php
/* code for segment one
......
*/
echo 1;
/* code for segment two
......
*/
echo 2;
/* code for segment three
......
*/
echo 3;
?>
Now most of you must have figured out that this script will ultimately produce an output as a string like '123' but I want each output sent one after the other. Is something like this possible? If yes please share an example.
Upvotes: 3
Views: 172
Reputation: 1379
Php is synchronous so it executes codes line by line, and long action are blocking.
If you dont want to wait script response you can use diferent php files and diferent ajax call to simulate asynchronous execution.
$.ajax({
url: 'yourfile1.php',
method: 'post',
data: {
}
}).done(function(response){
$.ajax({
url: 'yourScript2.php',
method: 'post',
data: {
toPost: response
}
}).done(function(response2){
// Ajax finished
});
});
If you want real server asynchronous execution you can use nodejs on server side, witch has been created for that.
"Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. "
Upvotes: 1
Reputation: 32727
In theory php scripts can return output to the client during execution, but in my experience this is unreliable, because the webserver might cache it.
I would rather break down your large php script into smaller parts and call each one separately. Each smaller php script can then return a message to the client signaling its progress. Context can be shared between the smaller php script by using the session feature.
Upvotes: 1