Search code examples
jqueryhtmlfeed

News feed auto-refresh jquery


How can I get a news feed with automatic and live updates?

I want to write some text and in the same second, the text shows up in a timeline for my visitors.

Example: http://beyonceontop.com/live/grammy-awards-2014/


Solution

  • your text input HTML

    <form>
      <textarea>Type things here... </textarea>
      <button type="submit">Send</button>
    </form>
    

    jquery

    $('form').submit(function(e){
      e.preventDefault();
      var message = $(this).find('textarea');
      $.ajax('update-feed.php?message='+message);
    

    update-feed.php

    if(isset($_POST['message']){
      $feed = 'myfeed.php';
      $f = fopen($feed,'a+');
      fwrite($f,$_POST['message']))
      fclose($f);
    }
    

    page that displays feeds:

    <h1>Feeds:</h1>
    <div class="feed">include('myfeed.php');</div>
    
    <script>
      checkFeed = function(){
        $.ajax('myfeed.php',{success:function(){$('.feed').html(data)});
      }
    
      setTimeout(checkFeed(),5000) //check every 5 seconds
    </script>
    

    That's a very rudimentary example of how to achieve this. It basically accepts input on send, saves it to a file, retrieves that file to a page, and refreshes that page every 5 seconds.