title: PHP - Flushing While Loop Data with Ajax
body: <p><em>Using PHP</em>, I would like to make a while loop that reads a large file and sends the current line number when requested. <em>Using Ajax</em>, I'd like to get the current line count and print it out onto a page. <em>Using html buttons</em>, I'd like to be able to click and activate or terminate a javascript thread that runs only ONCE and calls the <em>ajax method</em>.</p>
  
  <p>I have given it a shot but for some reason, nothing prints unless I comment out the <code>echo str_repeat(' ',1024*64);</code> function and when it's commented out, it shows the entire loop result:</p>
  
  <p>1 row(s) processed.2 row(s) processed.3 row(s) processed.4 row(s) processed.5 row(s) processed.6 row(s) processed.7 row(s) processed.8 row(s) processed.9 row(s) processed.10 row(s) processed.</p>
  
  <p>In a single line instead of showing them in separate lines like:</p>
  
  <pre><code>1 row(s) processed.
  2 row(s) processed.
  3 row(s) processed.
  4 row(s) processed.
  5 row(s) processed.
  6 row(s) processed.
  7 row(s) processed.
  8 row(s) processed.
  9 row(s) processed.
  10 row(s) processed.
  </code></pre>
  
  <p>Also I'm not sure how to terminate the JavaScript thread. So 2 problems in total:</p>
  
  <pre><code> 1. It's returning the entire While loop object at once instead of each time it loops.
   2. I'm not sure how to terminate the JQuery thread.
  </code></pre>
  
  <p>Any ideas? Below is my code so far.</p>
  
  <p><strong>msgserv.php</strong></p>
  
  <pre><code>&lt;?php
  
  //Initiate Line Count
  $lineCount = 0;
  
  // Set current filename
  $file = "test.txt";
  
  // Open the file for reading
  $handle = fopen($file, "r");
  
  //Change Execution Time to 8 Hours
  ini_set('max_execution_time', 28800);
  
  // Loop through the file until you reach the last line
  while (!feof($handle)) {
  
      // Read a line
      $line = fgets($handle);
  
      // Increment the counter
      $lineCount++;
  
      // Javascript for updating the progress bar and information
      echo $lineCount . " row(s) processed.";
  
      // This is for the buffer achieve the minimum size in order to flush data
      //echo str_repeat(' ',1024*64);
  
      // Send output to browser immediately
      flush();
  
      // Sleep one second so we can see the delay
      //usleep(100);
  }
  
  // Release the file for access
  fclose($handle);
  
  ?&gt;
  </code></pre>
  
  <p><strong>asd.html</strong></p>
  
  <pre><code>&lt;html&gt;
      &lt;head&gt;
          &lt;script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;
  
          &lt;style type="text/css" media="screen"&gt;
              .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
              .new{ background-color:#3B9957;}
              .error{ background-color:#992E36;}
          &lt;/style&gt;
  
      &lt;/head&gt;
      &lt;body&gt;
  
      &lt;center&gt;
          &lt;fieldset&gt;
              &lt;legend&gt;Count lines in a file&lt;/legend&gt;
              &lt;input type="button" value="Start Counting" id="startCounting" /&gt;
              &lt;input type="button" value="Stop Counting!" onclick="clearInterval(not-Sure-How-To-Reference-Jquery-Thread);" /&gt;
          &lt;/fieldset&gt;
      &lt;/center&gt;
  
      &lt;div id="messages"&gt;
          &lt;div class="msg old"&gt;&lt;/div&gt;
      &lt;/div&gt;
  
      &lt;script type="text/javascript" charset="utf-8"&gt;
          function addmsg(type, msg){
              /* Simple helper to add a div.
          type is the name of a CSS class (old/new/error).
          msg is the contents of the div */
              $("#messages").append(
              "&lt;div class='msg "+ type +"'&gt;"+ msg +"&lt;/div&gt;"
          );
          }
  
          function waitForMsg(){
              /* This requests the url "msgsrv.php"
          When it complete (or errors)*/
              $.ajax({
                  type: "GET",
                  url: "msgsrv.php",
                  async: true, /* If set to non-async, browser shows page as "Loading.."*/
                  cache: false,
                  timeout:2880000, /* Timeout in ms set to 8 hours */
  
                  success: function(data){ /* called when request to barge.php completes */
                      addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                      setTimeout(
                      'waitForMsg()', /* Request next message */
                      1000 /* ..after 1 seconds */
                  );
                  },
                  error: function(XMLHttpRequest, textStatus, errorThrown){
                      addmsg("error", textStatus + " (" + errorThrown + ")");
                      setTimeout(
                      'waitForMsg()', /* Try again after.. */
                      "15000"); /* milliseconds (15seconds) */
                  },
              });
          };
  
          $('#startCounting').click(function() {
              waitForMsg();
          });
      &lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>test.txt</strong></p>
  
  <pre><code>1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  </code></pre>