title: HTML5 SSE get updated records from database
body: <p>It's my first question so I'll apologize in advance if it's not properly constructed.</p>
  
  <p>I have to get updated records from the database and display to the user. My first thought was to use AJAX, but after a lot of research (on SO included) I decided to use HTML5 SSE (Eventsource).</p>
  
  <p>I checked a lot of tutorials and tips and got a working code, so my question to you is:</p>
  
  <p>Is this the best way to do it? Am I doing anything wrong? I'm open to suggestions.</p>
  
  <p>Here's the code:</p>
  
  <p>Javascript from HTML/View File (using codeigniter btw):</p>
  
  <p><code>
      var source = new EventSource('site/update');</p>
  
  <pre><code>var lastId = '';
  
  source.onmessage = function (event) {
      if(event.data != lastId){
          var json_object = eval( '(' + event.data + ')'); 
          var list = '';                                       
          $.each(json_object, function() {
              list = list + this.name + ' - ' + this.phone;
          });
          $('#client').html(list);
          lastId = event.data;
      } 
  };                                        
  </code></pre>
  
  <p></code></p>
  
  <p>As you can see I created an IF just so it won't update unless it's a new content. Ideally the SSE would just return once it had a new content, but I tested using an alert function and it kept getting the same content over and over again, so I added the IF. PS. I have a list to display the records inside the DIV, but I couldn't post it on SO it kept giving me formatting error so I removed it from the post.</p>
  
  <p>Here's the Controller code:
  <code></p>
  
  <pre><code>public function update() 
  {
      $this-&gt;load-&gt;model('site_model');  
      $clients = $this-&gt;site_model-&gt;get_all('');  
      header("Content-Type: text/event-stream\n\n");  
      echo "data: " . json_encode($clients);  
  }
  </code></pre>
  
  <p></code></p>
  
  <p>The controller is pretty simple and it calls a model function that just queries all DB records matching the criteria I want. I won't post the model since it's just a query.</p>
  
  <p>Well here it is. I look forward to hear your opinions.</p>
  
  <p>Thanks.</p>