jump to navigation

Update Content Every X-seconds with Ajax Cals November 2, 2011

Posted by Tournas Dimitrios in JQuery.

This code-snippet demonstrates how to update some web page sections or a block content on a page every x seconds without page reloading . A real  life example of this functionality  could be Twitter search results that come out when there are new tweets  .  Another example could be a side-bar that displays stock market values  which are  updated   every 2 minutes without page reload . Behind the scenes an Ajax request will query our server that will respond with new content that is produced dynamically .  Key to this functionality is JavaScript’s built-in setInterval() function  wich   runs  some javascript function every X seconds . For example , the following code would pop alert box every five seconds :

setInterval( "alert('Hello')", 5000 );

Now consider we want to update the contents of an div-box  every 10 seconds . The following code will query a PHP enabled server that will respond with the time .

// The content into "time.php" file .
echo date("l, F d, Y h:i:s" ,time() );


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Update content with ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

<h1 id="box">Loading ...... </h1> 
<script type="text/javascript">
function upsh(){
// Assuming we have #box
setInterval("upsh()", 3000 );


JQuery has an AJAX function called “load”, which accepts three parameters ( only the first is mandatory ) : 

  1.  the page you want to load (url) , 
  2.  data you want to send (POST) — optional
  3.  a callback function  — optional . 

 Our example  requests data from a remote server , so only the first parameter is used  .  The server responds with a plain-text message which is appended  to the  ” #box ” tag  . In a real world application , the server  would carry out a web-service and respond in XML  ,  JSON  or JSONP format .



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s