Question

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/

Was it helpful?

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.

OTHER TIPS

In the example you gave they are using the following js to update <div id=update> with the content every 5 seconds:

  $(document).ready(function(){
    var callAjax = function(){
      $.ajax({
        method:'get',cache: false,
        url:'updates.php',
        success:function(data){
          $("#update").html(data);
        }
      });
    }
    setInterval(callAjax,5000);
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top