PHP – Flushing While Loop Data with Ajax

You’re confused as to how PHP and AJAX interact.

When you request the PHP page via AJAX, you force the PHP script to begin execution. Although you might be using flush() to clear any internal PHP buffers, the AJAX call won’t terminate (i.e., the response handlers won’t be called) until the connection is closed, which occurs when the entire file has been read.

To accomplish what you’re looking for, I believe you’d need a parallel process flow like this:

  1. The first AJAX post sends a request to begin reading the file. This script generates some unqiue ID, sends that back to the browser, spawns a thread that actually does the file reading, then terminates.
  2. All subsequent AJAX requests go to a different PHP script that checks the status of the file reading. This new PHP script sends the current status of the file reading, based on the unique ID generated in #1, then exits.

You could accomplish this inter-process communication through $_SESSION variables, or by storing data into a database. Either way, you need a parallel implementation instead of your current sequential one, otherwise you will continue to get the entire status at once.

Leave a Comment