My problem is that I need a PHP script to continously provide ouput at certein points of it's execution. I have workng AJAX to fetch the html but it only echos once the script is complete. Here is an example:
<?php
class test {
function test() {
echo '1';
sleep(20);
echo '2'
sleep(5);
}
}
I need some way to have the echo's actually displayed in the browser even though the function is still continuing. I have tried using global variables and session variables to no avail.
Thanks for the help!
I've seen many questions where people are trying to do this type of thing, but as far as I know it really isn't possible to do it the way you're trying to do it using only PHP and AJAX. In order for this to work using just AJAX rather than websockets or some other approach, you can break your script into separate pieces at the points where it needs to provide output, and provide the output as responses to separate AJAX requests. Here is a basic example of what I mean. The script on your page can start the process and makes repeated calls to step through the process until it's complete.
<button id="begin_process">Start</button>
<script type="text/javascript">
function step(step_number) {
$.get('test.php', {'step_number': step_number}, function(response){
console.log(response.message);
if (response.next_step) {
step(response.next_step);
}
}, 'json');
}
$(document).ready(function(){
$('#begin_process').click(function(){
console.log('go!');
step(1);
});
});
</script>
test.php:
<?php
class Test {
function step($step_number) {
switch ($step_number) {
case 1:
return array('next_step' => 2, 'message' => 'step 1 complete');
case 2:
sleep(20);
return array('next_step' => 3, 'message' => 'step 2 complete');
case 3:
sleep(5);
return array('message' => 'finished');
}
}
}
$test = new Test();
echo json_encode($test->step($_GET['step_number']));