How to use the ob_flush() function to return data to the browser in an animated way?

Asked

Viewed 1,357 times

2

I need help, I have an email sending system, I need to know what’s going on in the process back-end a log that returns to the browser, when triggering script, example I want to send email to 2 people.

When an email is sent it returns one echo '1° Email enviado', '2° Email enviado' for the browser then but in real time type progress bar I read about a few things about ob_start(), ob_flush() but I don’t quite understand, can anyone help me ?

1 answer

0

You can do it like this:

PHP:

set_time_limit(0); // coloca o tempo da requisição "infinito"

ob_start();

for ($i = 1; $i <= 10; $i++): // aqui sera o seu for para enviar o email este envia 10 emails
   echo '|'. $i;  // retornada o email que foi enviado(Ele é acumulativo).
   sleep(1); // substitua pela sua função de envio de emails;
   ob_flush();
   flush();
endfor;

ob_end_flush();

AJAX:

$.ajax({
  type: 'POST',
  url: '../../model/php/teste.php', // arquivo de envio dos emails
  xhrFields: {
    onprogress: function(e) {
      var data = e.currentTarget.response;
      var atual = data.slice((data.lastIndexOf('|') + 1));
      console.log(atual);
    }
  },
  success: function(data) {
    console.log(data); // resultado final
  },
  error: function(data) {
    alert(data.responseText);
  }
});

See returning as emails are sent: inserir a descrição da imagem aqui

  • In case I have an Nginx it doesn’t run the flush ?

  • I don’t know Ginx, he, you should look for some method that can catch the progress of a request.

Browser other questions tagged

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