title: PHP and Twilio Real-time?
body: <p>I'm currently working on a real-time SMS System but I'm fairly positive that my current implementation is a terrible practice and I'm looking for guidance to be more efficient with this.</p>
  
  <h1>The Attempt</h1>
  
  <p>Currently, when you load up the interface it pulls all the text messages for that number you have selected. Then it fires off an ajax call every 5 seconds to the Twilio JSON PHP script I've written asking for messages newer than the last message in the list.</p>
  
  <pre><code>$.getJSON("/includes/twilio.php",{action:"getconvo",cid:customer.customer_number},function(data){
          $('#sms_messages').html("&lt;div&gt;&lt;/div&gt;");
          $(data.messages).each(function(){
              insertSMS(this.msg,this.date,this.from);
              lastMessage = this.date;
          });
          $("#sms_messages").animate({ scrollTop: $('#sms_messages &gt; div').height()},"fast");
          shouldUpdate = true;
          sms_interval = setInterval(function(){updateSMS(customer.customer_number)},5000);
  });
  </code></pre>
  
  <p>Update Function</p>
  
  <pre><code>function updateSMS(cid){
      if(shouldUpdate){
          $.getJSON("/includes/twilio.php",{action:"getconvo",cid:cid,date:lastMessage},function(data){
              if(data.messages.length &gt; 0){
                  // Play an embeded sound effect when a new message is found.
                  $('#sms_sound')[0].play();
                  $(data.messages).each(function(){
                      insertSMS(this.msg,this.date,this.from);
                      lastMessage = this.date;
                  });
                  $("#sms_messages").animate({ scrollTop: $('#sms_messages &gt; div').height()},"fast");
              }
          });
      }
  }
  </code></pre>