Receive data from a loop in a controller method in laravel view

1

I have a method in the controller that inserts a table, and I want the bar to increase for each insert, but this loop is in the controller. Is there any way to do that?

   //codigo javascript
$.ajax(
  {
    type: 'get',
    url: "{{ route('ruta') }}",
    data: { 'p1' : p1,
            'p2' : p2 },
    dataType: 'JSON',
    xhr: function() {
       var xhr = new window.XMLHttpRequest();
       xhr.addEventListener("progress", function(e){
           if(e.currentTarget.response.trim() == ''){
              recibidos++;
              aumentarBarra(recibidos);
            }
                        
       });
        return xhr;
    },
    success: function(data)
    {
      //codigo del success            
                
    }
 });         
//php
function Metodo(Request $request){
  
  @ini_set('zlib.output_compression', 0);
  header("Content-Type: text/html; charset=utf-8");
  if (ob_get_level() == 0) ob_start();
  
  .. la la la se hacen unas busquedas
  $ids = [1, 2, 3, 4];
  foreach($ids as $key => $id){
    //hacer un insert a la tabla
    
    echo ' ';
    ob_get_contents();
    ob_flush();
    flush();
  }
}

It works, but on the test server, I do not have access to the php.ini or the server settings, so I think the flush does not work, is there any other way to do it?

    
asked by Paola Casiano sipac 21.08.2018 в 19:54
source

1 answer

1

Mm you could keep the progress in session and in javascript execute a $ .get so you can return the progress of the action

Your javascript:

$.ajax(
  {
    type: 'get',
    url: "{{ route('ruta') }}",
    data: { 'p1' : p1,
            'p2' : p2 },
    dataType: 'JSON',
    beforeSend: function(){
        getProgreso();
    },
    success: function(data)
    {
      //codigo del success            

    }
 });

function getProgreso(){
    setInterval(function(){
            $.getJSON('/ruta-progreso', function(data) {
                //acá manejas el proceso con una barra o lo que estés usando
            });
        }, 1000);
}

On your controller:

public function getProgreso() {
    return response()->json(array(session('progresoInsert')));
}

public function Metodo(Request $request){

  @ini_set('zlib.output_compression', 0);
  header("Content-Type: text/html; charset=utf-8");
  if (ob_get_level() == 0) ob_start();

  .. la la la se hacen unas busquedas

  $ids = [1, 2, 3, 4];
  $progreso = 1;
  $total = count($ids);
  foreach($ids as $key => $id){
    //hacer un insert a la tabla

    echo ' ';
    ob_get_contents();
    ob_flush();
    flush();


    //podrías aplicar una regla de 3
    $progreso = (($progreso * 100) / $total);
    $progreso++;
    session(['progresoInsert' => $progreso]);
  }
}
    
answered by 22.08.2018 в 16:23