Flush frontend data output

Asked

Viewed 220 times

1

Well I’m following the example of php.net

    <?php
header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
  echo $i . '<br />';
  flush();
  ob_flush();
  sleep(1);
}
echo 'End ...<br />';
?> 

if I run this script directly in the browser it counts from 1 to 10 showing its result correctly...

However I have a textarea that receives the item , and ajax to send the post and search the result on the screen according to the result

more when I send the items, the flush doesn’t work only returns me the result at the end of the for

     <script type="text/javascript">
$(document).ready(function() {
    $("#enviar").click(function() {
        var nome = $("#nome");
        var nomePost = nome.val(); 
        $.post("flush.php", {nome: nomePost},
        function(data){
         $("#resposta").html(data);
         }
         , "html");
    });
});
</script>



    <form action="" method="post">
      <textarea name="nome" id="nome" cols="45" rows="5"  required placeholder="Sua lista bla bla bla bla..."></textarea>
      <br /> 
      <br />
     </form>
     <button id="enviar" type="submit" class="ls-btn-primary ls-btn-xs">Check !</button>
      <br>
    </h6>

<br>

  <div  id="resposta"> Aguardando lista!</div>
  • Maybe where is var nome = $("#nome"); Should be var nome = $("#nome").attr("name");

  • Hello Wender, welcome to [en.so]! Very interesting your question. But maybe you’re using the wrong technique. If you need a mechanism to send data to the customer bit by bit asynchronously, maybe Websockets whatever you’re looking for. However, if the idea is to display something progressively on the screen, the scenario changes completely. It would be better to explain your purpose better. Hug!

1 answer

1

The customer even receives the data each flush supposedly, however ajax only delivers the end result, ie ajax will only give you something when readyState is equal to 4 (equals complete).

To receive part by part you need to create multiple requests using the GET or SESSION method. I believe you will use this with real data, in case I added an example just to simulate the situation, if it is database you can check with mysqli_num_rows and LIMIT ?,? (offset and limit) returned 0, being the result equal to zero then you can use:

if (mysqli_num_rows($result) === 0) {
    echo 'final';
    exit;
}

Create a file called chunkdata.php

<?php
header( 'Content-type: text/html; charset=utf-8' );

$offset = isset($_GET['offset']) ?   0 : $_GET['offset'];
$limit  = empty($_GET['limit'])  ?  10 : $_GET['limit'];

if ($offset > 100) {
    //E você pode criar uma fork para limitar as requisições quando chegar ao resultado final, neste caso é apenas um exemplo para simular
    echo 'final';
    exit;
}

for( $i = $offset; $i < $limit; $i++)
{
  echo $i . '<br />';
}
?> 

And the delay would be on the front end, something like:

function getData(nomePost, offset) {
    var delay = 1000;//Delay das requisições
    var limit = 10;//O limite da consulta será de dez em dez
    offset = offset || 0;//Se for undefined usa 0

    $.post("chunkdata.php?offset=" + offset + "&limit=" + limit,
        {
            "nome": nomePost
        }, function(data) {
            //Se o servidor retornar a palavra "final" então isto irá interromper o loop
            if (data !== "final") {
                 return;
            }
            var lastData = $("#nome").html();
            $("#nome").html(lastData + data);

            //Roda o script novamente
            setTimeout(getData, delay, nomePost, offset);
    }, "html");
}

$(document).ready(function() {
    $("#enviar").click(function() {
        getData($("#nome").val());
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.