Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8535043
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T10:20:16+00:00 2026-06-11T10:20:16+00:00

I’m playing a bit around with push notifications, and want to update a page

  • 0

I’m playing a bit around with push notifications, and want to update a page whenever there’s a change in the database.

I have this from http://www.screenr.com/SNH:

<?php
$filename = dirname(__FILE__).'/data.php';

$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);

while ($currentmodif <= $lastmodif) {
  usleep(10000);
  clearstatcache();
  $currentmodif = filemtime($filename);
}

$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>

My data.php is a script getting data from a JSON file:

<script>function itnews_overview() {
    $.getJSON('/ajax.php?type=itnews_overview', function(data) {
        $.each(data.data, function(option, type) {
            $('.bjqs').append('<li><span class="date">'+ type.submitted +'<br />'+     type.time +'</span><h2>' + type.title + '</h2><p>' + type.content + '</p></li>');
        });

    });

}
</script>

<script>
  itnews_overview();
</script>
<div id="news">
  <ul class="bjqs"></ul>
</div>

UPDATE: Code from index.php:

<script type="text/javascript">

  var timestamp = null;

  function waitForMsg() {
$.ajax({
  type: "GET",
  url: "getData.php?timestamp=" + timestamp,
  async: true,
  cache: false,

  success: function(data) {
    var json = eval('(' + data + ')');
    if(json['msg'] != "") {
      $(".news").html(json['msg']);

    }


    timestamp = json['timestamp'];
    setTimeout('waitForMsg()',1000);        
  },

  error: function(XMLHttpRequest, textStatus, errorThrown){
    setTimeout('waitForMsg()',15000);
  }

});
  }

  $(document).ready(function(){
  waitForMsg();
});

</script>

As this file isn’t saved when I add something to the database, filemtime won’t work — is there another way I can check if new rows has been added to the table?

UPDATE: Trying to solve this with SSE.
I have two files, index.php and send_sse.php (inspiration from http://www.developerdrive.com/2012/03/pushing-updates-to-the-web-page-with-html5-server-sent-events/)

index.php:

<div id="serverData">Content</div>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
    //create an object, passing it the name and location of the server side script
    var eSource = new EventSource("send_sse.php");
    //detect message receipt
    eSource.onmessage = function(event) {
        //write the received data to the page
        document.getElementById("serverData").innerHTML = event.data;
    };
}
else {
    document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>

send_sse.php:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$url = "content.json";
$str = file_get_contents($url);
$data = json_decode($str, TRUE);
//generate random number for demonstration
//echo the new number
echo "data: " . json_encode($data);


ob_flush();
?>

This, however, doesn’t seem to work, which is probably because SSE needs plain text data. I just can’t figure out how to do that and then wrap that content in a couple of HTML tags.

UPDATE: Okay, so now it’s sort of working with SSE, thanks to VDP. I have the following:

$sql= "SELECT title, content, submitted FROM `flex_itnews` where valid = 1 order by submitted desc";
$query= mysql_query($sql);
setlocale(LC_ALL, 'da_DK');
while($result = mysql_fetch_array($query)){
    echo "data: <li><span class='date'>". strftime('%e. %B', strtotime($result['submitted'])) ."<br />kl. ". strftime('%H.%M', strtotime($result['submitted'])) ."</span><h2>" . $result['title']. "</h2><p>" . $result['content'] ."</p></li>\n";
}

However, when I add anything new, it just echoes data: data: data. If I refresh the page, it displays correctly.

UPDATE: Using livequery plugin:

    <script>
      var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        $('.bjqs').html(event.data);
      };

      $('#news').livequery(function(){
        $(this).bjqs({
          'animation' : 'slide',
          'showMarkers' : false,
          'showControls' : false,
          'rotationSpeed': 100,
          'width' : 1800,
          'height' : 160
        });
      });

  </script>

UPDATE: Trying to use delegate()

    <script>
      $("body").delegate(".news", "click", function(){
        $("#news").bjqs({
          'animation' : 'slide',
          'showMarkers' : false,
          'showControls' : false,
          'rotationSpeed': 100,
          'width' : 1800,
          'height' : 160
        });
                var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        $('.bjqs').append(event.data);
      };
      });
  </script>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T10:20:17+00:00Added an answer on June 11, 2026 at 10:20 am

    Yes! There are multiple (better) ways:

    1. websocket (the best solution but not supported on older or mobile browsers)
    2. Server sent events (SSE) (sort of polling but optimized just for the task you ask for)
    3. Long polling (like you are doing)
    4. Flash sockets
    5. other plugin based socket stuff
    6. ajax polling

    I’ve posted another answer with examples about it before

    I listed several transport methods. websockets being the ideal (because it’s the only 2 way communication between server and client), SSE being my second choice. You won’t need the $.getJSON method. The overall idea will be the same.

    On the server side (php in your case) you query your database for changes. You return the data as JSON (json_encode(data) can do that). On the client side you decode the JSON (JSON.parse(data) can do that). With the data you received you update your page.

    Just the polling like you where doing causes more overhead because you are doing lots of request to the server.

    SSE is more “I want to subscribe to a stream” and “I want to stop listening”. => less overhead

    Websockets is more: “I set up a connection. I talk server listens. Server talks client listens” A full duplex connection. => least overhead

    SSE Code example

    The page the client goes to (for example index.html or index.php)

    It’s just a normal html page containing this javascript:

    <html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
        <script>
            //javascript:
            var source = new EventSource('data.php');
            source.onmessage = function (event) {
                //here you do the stuff with the received messages.
                //like log it to the console
                console.log(event.data);
                //or append it to div
                $('#response').append(event.data);
            };
        </script>
    </head>
    <body>
        <div id="response"></div>
    </body>
    </html>
    

    The ‘data.php’ page:

    <?php
    /* set the header first, don't echo/print anything before this header is set! Else the default headers will be set first then this line tries to set the headers and results in an error because the header is already set. */
    header("Content-Type: text/event-stream\n\n");
    
    //query the database
    $sql= "SELECT COUNT(*) FROM `messages`";
    $query= mysql_query($sql);
    $result = mysql_fetch_array($query);
    $count = $result[0];
    
    //return the data
    echo "data: " . $count. "\n";
    ?>
    

    So you only need those 2 pages.

    UPDATE:

    I had only seen your comments not the updates.. sorry 😉

    if you use .delegate() you shouldn’t use body but try a selector as high up the tree as possible (.bjqs in your case).

    In you’re case you don’t even need live,delegate,on or all that! Just apply the bjqs again afther the content is updated.

      var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        $('.bjqs').html(event.data);
        $("#news").bjqs({
          'animation' : 'slide',
          'showMarkers' : false,
          'showControls' : false,
          'rotationSpeed': 100,
          'width' : 1800,
          'height' : 160
        });
      };
    

    This will give you issues too because you are constantly re-initializing bjqs and it isn’t written to handle dynamically updating content. What you can do is send only data (with php) if there is new data. Check if the call returns empty, if not update:

      var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        if(event.data !=""){
            $('.bjqs').html(event.data);
            $("#news").bjqs({
              'animation' : 'slide',
              'showMarkers' : false,
              'showControls' : false,
              'rotationSpeed': 100,
              'width' : 1800,
              'height' : 160
            });
        }
      };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
This could be a duplicate question, but I have no idea what search terms
I know there's a lot of other questions out there that deal with this
I have a view passing on information from a database: def serve_article(request, id): served_article
I have a reasonable size flat file database of text documents mostly saved in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.