'how to send percent progress in laravel controller with for and flush()

how can i do to return values ​​from inside the for one by one, to inside ajax. I'm trying to use flush() but I'm not getting the result I want, because it executes everything for later to bring me the values. and I need the values ​​to be printed one by one until the end of the for. here is the controller part:

    public function store(Request $request){
        for($i = 1; $i <= 100; $i++){
            echo json_encode(['percent' => $i]);
            ob_flush();
            flush();
            sleep(1);
        }
    }

here is the ajax part:

         $.ajax({
           
            url: "{{route('percent.do')}}",
            type: "post",
            data: new FormData(this),
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(data){
                console.log(data);
            }
        });

and here is the route part:

Route::post('percent/do', [PercentController::class, 'store'])->name('percent.do');

I would like it to bring me the result in console.log(data) like this:

  1
  2
  3
  4
  5
  ...

but it executes all the for to later bring me the result and that's not what I want



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source