2

ag.php

<?php  
ignore_user_abort(true);
set_time_limit(0);
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
$i=0;
while(1){
    echo $i;
    $i++;
    ob_flush();
    flush();

    if (connection_aborted()){
        break;
    }

    usleep(1000000);
}

ajax:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    console.log(xhttp.readyState+" "+xhttp.status);
    if (xhttp.readyState === 3 && xhttp.status ===200) {
        console.log(xhttp.responseText+"\n");

    }
};
xhttp.open("GET", "ag.php", true);
xhttp.send();

hi, at above code, i want to make a persistent connection with php and echo data in while block in 1 second interval and data comes browser like this;
0
01
012
0123
...
but i want echo data to browser like;
0
1
2
3
...
but couldn't achive it so i found this [How to clear previously echoed items in PHP about my question but not exactly what i want i think. anybody know is there any way to empty/remove previous echoed data? is it possible? help please.

SidOfc
  • 4,552
  • 3
  • 27
  • 50
Ümit Sezer
  • 23
  • 1
  • 3
  • are using div or not ? – krishn Patel Feb 07 '17 at 06:38
  • viewing it in console.log – Ümit Sezer Feb 07 '17 at 06:41
  • 1
    Your PHP code do what you want (except the `ob_flush()` which failed because `ob_start()` was not called). It's the Javascript code which seems to keep the full response data, which is not surprising. Maybe resetting it to empty string (or null) after each read may work. – Damien Flament Feb 07 '17 at 07:05
  • As you are using your asynchronous HTTP request as a pipe (your server never close the connection) you may need to manage a local buffer (in your client-side script). – Damien Flament Feb 07 '17 at 07:08

2 Answers2

4

use substr()

var xhttp = new XMLHttpRequest();
var lastResponse = '';
xhttp.onreadystatechange = function() {
    //console.log(xhttp.readyState+" "+xhttp.status);
    if (xhttp.readyState === 3 && xhttp.status ===200) {

        var currentAnswer = xhttp.responseText.substr(lastResponse.length);
        lastResponse = xhttp.responseText;
        console.log(currentAnswer+"\n");

    }
};
xhttp.open("GET", "ag.php", true);
xhttp.send();
Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48
reza
  • 1,746
  • 6
  • 16
  • 32
2

Perhaps ob_clean is what you are looking for.

void ob_clean ( void )

This function discards the contents of the output buffer. This function does not destroy the output buffer like ob_end_clean() does. The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

Raptor
  • 53,206
  • 45
  • 230
  • 366
timestee
  • 1,086
  • 12
  • 36