title: Server-Sent Events with PHP
body: <p>I have a web app which sends some data from a js script to a php server which inserts it into a mysql database. I also need to notify all other clients that the data has been sent and send it to them. </p>
  
  <p>I'm trying to use Server-Sent Events to do this but I'm having some trouble grasping the concept. Here's my code:</p>
  
  <pre><code>$(document).ready(function() {
      var source = new EventSource("../Server/insertMessage.php");
      if(typeof(EventSource) == "undefined") {
          alert("event source doesnt work");
      } else { alert("event source works"); }
  
      source.onmessage = function(event) {
          alert(event.data);
          // do stuff with event.data
      };
  });
  </code></pre>
  
  <p>Elsewhere in my js script, I send an AJAX request to insertMessage.php with POST parameters as the data details. Does this trigger the server-side event? Here's my server side code:</p>
  
  <p><strong>insertMessage.php</strong></p>
  
  <pre><code>if(isset(// check POST to see if the right request was sent)) {
      // insert data into database
      // ...
      // ...
  
      // Send the new data to listeners
      header('Content-Type: text/event-stream');
      header('Cache-Control: no-cache');
      // Create data array
      $dataArray = array("data" =&gt; $data, "moreData" =&gt; $moreData);
      // Encode JSON
      $callback = json_encode($dataArray);
      // Send it
      echo "data: $callback";
      flush();
  }
  </code></pre>
  
  <p>While the "event source works" alert is sent, I never get the <code>event.data</code> alert, even though I am making the AJAX call to <code>insertMessage.php</code>. I may not completely understand Server-Sent Events yet. What am I doing wrong?</p>