I'm trying to get some live output from an AJAX request.
This is the code I'm using:
$.ajax({ type: "GET",
url: "test.php?delete=students",
async: true,
success : function(data) {
console.log(data)
}
});
When triggered by a link on my web page a spinning animation is shown to show that something is happening. I'd also like to show in a div
the output from test.php as it is running.
test.php has a simple loop which loops through all students and deletes them, it then echo "$student removed";
When run from the command line the removals are shown, when run via AJAX I only get the animation not the output.
I'm not sure how to get that, I've tried a couple of plugin's with out much success. I've also tried to use XMLHttpRequest
and responseText
but i'm not sure how to use this correctly.
Ideally I'd like each removal to be shown in a #status
div.
Can any one advise how to do this ?
UPDATE
progress : function(data) {
console.log(data);
},
I've added the above and move I get some output in the console. ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 44, total: 0, type: "progress"…}
Expanding that I can see the responsetext which contains the data I'm after. How do I get that so I can append it to a div
?
You may try using Server-sent events for it: https://html.spec.whatwg.org/multipage/comms.html#server-sent-events
Client code will be simple:
var sse = new EventSource('test.php?delete=students');
sse.addEventListener('message', function(e) {
console.log(e.data);
}, false);
In your test.php code will look something like the following:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
for ($i = 0; $i < ob_get_level(); $i++) {//for each open buffer
ob_end_flush();//close it
}
ob_implicit_flush(1);//turn implicit flush on
//now goes what you called "loops through all students and deletes them"
while(1) {
/*here you post your code that deletes your student*/
$data = "$student removed";//message to send to client confirming deleting of particular student
echo "data: ".$data . PHP_EOL;//here you send data to client, it will receive it and handle inside 'message' event handler
echo PHP_EOL;//need this just to fulfill the SSE standard
sleep(1);//use if need to insert pause between sending new portion of data (better use it to keep your browser safe from too much of messages per second)
}
Don't forget to break your loop after finishing deleting students=)