How to use the ob_flush () function to return data to browser animatedly?

2

I need a help, I have an email system, I need to know what is going on in the backend process 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 a echo '1° Email enviado', '2° Email enviado' to the browser then but in real time type progress bar I read about some things about ob_start() , ob_flush() but I do not quite understand, can someone help me?

    
asked by anonymous 16.02.2016 / 20:07

1 answer

1

You can do 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 email sending progress:

    
16.02.2016 / 20:32