Search code examples
xmlhttprequestcodeigniter-4

how to show results one by one in codeigniter 4 for loop with ob_flush


my problem is: i wan to show data in real time with codeigniter 4

This code results will be out once the for loop is ended

what i wan to do is echo results one by one

i have alrady done this before but not with codeigniter, it's was my own code without any framwork

but now i am stiked here 1 week and no rsults

i use codeigniter 4

and i use aapanel in my server

and this is my phpinfo my php info

my function in my controller Count.php

function startcounter(){
    $count = $this-\>request-\>getPost("count");
    if (ob_get_level() == 0) ob_start();
    for($i=0; $i\<=$count; $i++){
        echo $i;
        ob_flush();
        flush();
        sleep(1);
    }
    ob_end_flush(); 
    exit();
}

My javascript

function startcounter(){
    data = "count=5";
    var xhr = new XMLHttpRequest();
    xhr.open('POST', baseUrl+'/count/startcounter', true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(data);  
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 1) {
            resp = xhr.response;
            arrs = resp;
            if (xhr.readyState == XMLHttpRequest.LOADING) {
                console.log(xhr.responseText);
            }
            if (xhr.readyState == XMLHttpRequest.DONE) {
                alert('Done')
            }
        }
    }
    
    
}

Solution

  • function testflush(){
        ini_set('output_buffering','on');
        ini_set('zlib.output_compression', 0);
        ini_set('max_execution_time', '3000');
        ob_implicit_flush();
        $response = service('response');
        $response->send();
        ob_end_flush();
        flush();
        for($i=0; $i<=99; $i++){
           echo "Test".$i;
           ob_flush();
           flush();
           sleep(1);
        }
      return $this->response->setJSON(''); // send empty json response (This is 
      the most important thing)
    }