Auto div refresh with AJAX

Hello,

I am showing recent visitors on profile page.The most recent visitor would be “1 min ago”.If suddenly new user comes so i just want to append that user with the message “about a min ago” without refreshing the page.

ex- suppose my recent visitors list ll be like this-

asha
rahul
vineet
meera
aniket

and now smita comes as the recent most visitor i want to append her name in to this list without refreshing the the entire page like this

asha
rahul
vineet
meera
aniket
smita

I know i can do this with AJAX. I have searching around the net for the any helpful resource but didn’t get anything yet.

Can anyone please tell me whether is a possible or not.

Thanks in advance.

Try something like this:


<!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" xml:lang="en" lang="en">
<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
	<title>JavaScript Timer</title>
</head>
<body>
<script type="text/javascript"> 
	var second = 0;
	var limit = 15;
	function display(){ 
		if (second == limit){
			var rand = new Date().getTime();
			var myVal = '1';
			$.post('getusers.php?rand=' + rand, {myVar : myVal}, function(data){
				// show the data variable in a div
			});
			second = 0; 
		}
		second += 1;
		setTimeout("display()", 1000);
	}
	display();
</script> 
</body>
</html>

This will send an AJAX request in every 15 seconds and will print out the content that the getusers.php file will output in data variable. Hope this will help you. I have used jQuery AJAX. You can use your own AJAX script as well.

Thanks for your reply Raju,

Tried your code but i am not getting anything except “Hello”. what you think what i am missing here?

Here is the code-
Try.html

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>JavaScript Timer</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
    var second = 0;
    var limit = 15;
    function display(){
        if (second == limit){
            var rand = new Date().getTime();
            var myVal = '1';
            $.post('select.php?rand='+rand, {myVar : myVal}, function(data){
                // show the data variable in a div
            });
            second = 0;
        }
        second += 1;
        setTimeout("display()", 1000);
    }
    display();
</script>
<body>
Hello
</body>
</html>

select.php

<?php
include("includes/config.php");
$sql = mysql_query("Select ename from table1");
$record_count=mysql_num_rows($sql);
//Display count.........
if(mysql_num_rows($sql) > 0){
while($row = mysql_fetch_array($sql)){

echo $row['ename'];
echo "<br/>";

}
}

echo $record_count;
@mysql_free_result($sql);
?>

You should have a container element (div) in the page in which then you need to insert the AJAX returned content.

Try something like this:


<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>JavaScript Timer</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
    var second = 0;
    var limit = 15;
    function display(){
        if (second == limit){
            var rand = new Date().getTime();
            var myVal = '1';
            $.post('select.php?rand='+rand, {myVar : myVal}, function(data){
                // show the data variable in a div
                $('#showUsers').html(data);
            });
            second = 0;
        }
        second += 1;
        setTimeout("display()", 1000);
    }
    display();
</script>
<body>
<div id="showUsers"></div>
</body>
</html>

It will fetch the users from the database in every 15 seconds.

Needless to say that its working now. :slight_smile:

But i am mootool user and i have some mootool effects on the page where i want to put this recent visitor code.

I have used jQuery AJAX. You can use your own AJAX script as well.

Could you please tell me how can i achive this using only AJAX?

The following are my own AJAX methods which work so far.

And you can use this in the above example:


<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>JavaScript Timer</title>
	<script type="text/javascript">
	    /**
		* @filename JsAjax.js
		* @author Raju Gautam
		* @version 0.1
		* @copyright Copyright (c) 2007, Author Raju Gautam 
		* @package AJAX Collection
		* @date Dec 31, 2007
		**/
		/* Loading script */
		var strLoading = '<div style="padding:2px;color:#FF0000;"><img src="images/ajax-loader.gif" /> Loading...</div>';
		
		/****************** AJAX GET Start **************************/
		/*
		* This is the function to send the request to the server
		* @author Raju Gautam
		* @version 0.1
		* @copyright Copyright (c) 2007, Raju Gautam
		* @date Dec 31, 2007
		**/
		function sendGetRequest(para_url, contentDiv, divLoading){
			var url = "";
			var xmlHttp = GetXmlHttpObject();
			if(para_url.indexOf('?')) url = para_url + "&rand=" + Math.random();
			else url = para_url + "?rand=" + Math.random();
			
			xmlHttp.onreadystatechange = function(){
				afterStateChange(xmlHttp, contentDiv, divLoading);
			}
			xmlHttp.open("GET", url, true);
			xmlHttp.send(null);
		}
		
		/* This is the function to used to show the response text from server
		* @author Raju Gautam
		* @version 0.1
		* @copyright Copyright (c) 2007, Raju Gautam
		* @date Dec 31, 2007
		**/
		function afterStateChange(xmlHttp, contentDiv, divLoading){ 
			if(xmlHttp.readyState < 4){
				showLoading('On', contentDiv, divLoading);
			}
			if(xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){
				showLoading('Off', contentDiv, divLoading);
				document.getElementById(contentDiv).innerHTML 	= xmlHttp.responseText
			}
		}
		
		/* This is the function to show/hide the loading message
		* @author Raju Gautam
		* @version 0.1
		* @copyright Copyright (c) 2007, Raju Gautam
		* @date Dec 31, 2007
		**/
		function showLoading(flag, contentDiv, divLoading){ 
			if(divLoading != ''){
				var objLoading = document.getElementById(divLoading);
				if(!objLoading) var objLoading = document.getElementById(contentDiv);
				if(flag == 'On') objLoading.innerHTML = strLoading;
				else if(flag == 'Off') objLoading.innerHTML = '';
			}
		}
		
		/*
		* This is the function to create a new XML HTTP object GET Request
		* @author Raju Gautam
		* @version 0.1
		* @copyright Copyright (c) 2007, Raju Gautam
		* @date Dec 31, 2007
		**/
		function GetXmlHttpObject(){
			var xmlHttp;
			try{
				/* Firefox, Opera 8.0+, Safari */
				xmlHttp = new XMLHttpRequest();
			}
			catch (e){
				/* Internet Explorer */
				try{
					xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e){
					try{
						xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch (e){
						alert("Your browser does not support AJAX!");
						return false;
					}
				}
			}
			return xmlHttp;
		}
		/****************** AJAX GET End **************************/
		var second = 0;
	    var limit = 15;
	    function display(){
	        if (second == limit){
	            var rand = new Date().getTime();
	            var myVal = '1';
	            sendGetRequest('select.php?rand='+rand, 'showUsers', 'showUsers');
	            second = 0;
	        }
	        second += 1;
	        setTimeout("display()", 1000);
	    }
	    display();
	</script>
</head>
<body>

<body>
<div id="showUsers"></div>
</body>
</html>

Sorry for the late reply.

I think as of now this auto refresh with Jquery is fine for me.

Thank you.:slight_smile:

I have different div on the same page. And i am applying this for particular div(lets say “recent”)
then how can i get this result exactly there only.Now the status is its coming on top of the page.

I was trying somthing like this

$(document).ready(function() {
    $("recent").click(function(event) {
        //my code
    });
});

but it ll work after the click only.

so my question is how we can call this js for the exact particular div?

Just replace this line:


$('#showUsers').html(data);

to


$('#recent').html(data);

Done. :weee:

<script type="text/javascript">
function getRefresh() {
$("#auto").load("select.php?user='<?=$user;?>", '', callback);
}
function callback() {
setTimeout("getRefresh();", 1000);
}

$(document).ready(getRefresh);
</script>


Hello Raju,
I didn’t see your reply.such easy solution you have given. :frowning:

thanks a lot.