title: PHP jQuery Long Polling Chat Application
body: <p>I've made a simple PHP jQuery Chat Application with Short Polling (AJAX Refresh). Like, every 2 - 3 seconds it asks for new messages. But, I read that Long Polling is a better approach for Chat applications. So, I went through some Long Polling scripts.
  I made like this:</p>
  
  <h2>Javascript:</h2>
  
  <pre><code>$("#submit").click(function(){
      $.ajax({
          url: 'chat-handler.php',
          dataType: 'json',
          data: {action : 'read', message : 'message'}
      });
  });
  
  var getNewMessage = function() {
      $.ajax({
          url: 'chat-handler.php',
          dataType: 'json',
          data: {action : 'read', message : 'message'},
          function(data){
              alert(data);
          }
      });
  
      getNewMessage();
  }
  
  $(document).ready(getNewMessage);
  </code></pre>
  
  <h2>PHP</h2>
  
  <pre><code>&lt;?php
      $time = time();
      while ((time() - $time) &lt; 25) {
          $data = $db-&gt;getNewMessage ();
  
          if (!empty ($data)) {
              echo json_encode ($data);
              break;
          }
  
          usleep(1000000); // 1 Second
      }
  ?&gt;
  </code></pre>
  
  <p>The problem is, once <code>getNewMessage()</code> starts, it executes unless it gets some response (from chat-handler.php). It executes recursively. But if someone wants to send a message in between, then actually that function <code>($("#submit").click())</code> never executes as <code>getNewMessage()</code> is still executing. So is there any workaround?</p>