Wireless Army
This is a blog / tips and tricks website for web developers and security researchers.
follow us in feedly


real time update from php
by admin
 at 2016-11-17 11:22:00.

the following is really useful if you want a real time update of something with ajax

if you have a php for loop like the following:

for ($i = 0; $i < 5; ++$i) {
    echo $i." ";
    sleep(1);
}

if will run the loop and then give you all the numbers at the same time. But what you want it to show you the one number per second.

you will have to add ob_flush and flush:

for ($i = 0; $i < 5; ++$i) {
    echo $i." ";
    ob_flush();
    flush();
    sleep(1);
}

you can also set a time limit like so

set_time_limit(30);

and make sure it doesn't stop if user closes the page

ignore_user_abort();

now if you want to use ajax, the following is useless

$.ajax({
type: 'POST', url: '/test.php',
data: "test=test"
}).done(function (msg) {
    alert(msg);
}
}).fail(function (jqXHR, textStatus) {
    console.log("error");
});

because it will only detect a 4 ready status

0: request not initialized 
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
var http = new XMLHttpRequest();
var url = "/test.php";
var params = "test=test";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
    var msg = http.responseText;
    if(http.readyState == 4 && http.status == 200) {
        alert(msg);
    }else if (http.readyState > 2 ){
       alert(msg);
    } }
http.send(params);