简体   繁体   中英

PHP flush information in controller

I am trying to send data to view from controller in PHP CodeIgniter.
I am calling the PHP function through ajax and using ob_flush to send data back but the problem is that all the flush calls are concatenated in later calls.

For example: the first flush send 1 second flush call send 12 instead of 2 .

This is my controller loop.

foreach ($csv_array as $row) {
    ob_start();
    $varint=$varint+1;
    echo $varint;
    $content = ob_get_contents();
    ob_end_clean();
    echo $content;
    ob_flush();
    flush();
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
}

My ajax call is this:

document.getElementById('upld').onclick = function() {
    xhr = new XMLHttpRequest();
    var mydata = new FormData($('#form')[0]);
    xhr.open("POST", base_url+"index.php/controller/function", true);
    xhr.onprogress = function(e) {
        console.log(e.currentTarget.responseText);
    }
    xhr.onreadystatechange = function(data='') {
        if (xhr.readyState == 4) {
            console.log(myArr);
        }
    }
    xhr.send(mydata);
};

Documentation for flush() says:

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

In your case you can replace flush() with ob_flush() as I don't think you are looking to flush the system output buffers.

As a little extra this code:

$content = ob_get_contents();
ob_end_clean();

Can be condensed into one function call that is an alias for both of the previous commands combined:

$content = ob_get_clean();

Documentation for ob_get_clean()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM