I'd like to query the database every five seconds to see if there are any new posts (new nodes).

I'm trying to query the database every five seconds by running a JavaScript function so I don't have to do a page refresh, but the results I get are not the most up-to-date results (they are the results from when the page was first loaded). I'm a beginner at Javascript/AJAX, so I'm sure I'm doing it wrong - expecially cuz I've never seen php code inside Javascript code, but I don't know any other way to do this. Here is the code I'm using:

In the <head> of my page.tpl.php file:

<SCRIPT type="text/javascript">

function checkformoreposts()
  // get the current time timestamp when page is first loaded
  if (!(isset($original_time))) {
    $original_time = time();

  // be sure all variables are reset
  $qry_result = NULL;
  $result = NULL;
  $created = NULL;
  $sql = NULL;
  $row = NULL;
  $numberofposts = 0;

  // query the database to find how many posts have 'created' timestamps that are later than the original page-load time
  $sql = "SELECT created FROM {node} WHERE created > ($original_time)";
  $qry_result = db_query($sql);
  while($row = db_fetch_array($qry_result)) {
    $created[] = $row['created'];
  $numberofposts = count($created);
document.getElementById('my_text').innerHTML += "There are <?php print $numberofposts; ?> new posts since time <?php print $original_time; ?>. ";


In the <body> of my page.tpl.php file:

<SCRIPT type="text/javascript">



<div id="my_text"></div>

The code executes fine, but it doesn't get newer results every five seconds, even when there are new posts with later timestamps. I think I need to do this by using AJAX to "poll the server," which is just a phrase I keep finding on the web, but don't know what it is or how to do it. I'm a beginner at JavaScript and AJAX, so any help would be soooo awesome!

Andrew G


cerup’s picture

Did you get any farther on this? Based on your post here: http://drupal.org/node/460890 we're trying to do similar things.

BigMike’s picture


I am also learning how to use AJAX but one thing I know right away from your script is that PHP code is only ran once, and then sent to the client's browser. Therefore the query you are using will only be executed once per page load and this is why you are not seeing any additional information.

As far as I know simple javascript cannot execute any server-side scripts, like PHP, which is where AJAX comes in ... but this part I am still trying to learn! (I do not see any AJAX in your code at all)

But anyway, your script is working properly, it's just that it's PHP is never re-executed unless the page is reloaded.