So you have a div that you would like to be up to date on your site without having the page refresh?
This small script will allow you do this. Let’s say that you want to show the total number of users on your site as your site is blowing up and you want visitors to see the number grow.
firstly…load jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
next, we need to build the script in the “head” section of your page. This script targets a div with a loaded php file and sets how often the div should be reloaded
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('/path/to/your/php/file/userCount.php');
}, 3000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
here are the contents of “userCount.php”
require "/path/to/your/database/connection/connection.php";
$userCount = mysql_query( "SELECT * FROM users" ) or die("SELECT Error: ".mysql_error());
$numRows = mysql_num_rows($userCount);
echo $numRows;
here is the div in the html. you can place “loading users…” or a “loading” image inside of the div and it will be replaced by the results of “userCount.php”
<div id="results">Loading users...</div>
Matthew A Price
Chris
Matt,
Thanks for posting your div refresh code–it was just what I was looking for!
The problem I’m having is that the Table Sorter plugin (and really any JQuery code) that is part of that refreshing Div does not ‘execute’ after the first refresh. Do you know how to fix this issue?
Thanks!
Matthew Price Post author
Hi Chris
As the AJAX content is not loaded with the DOM, you do not have access run new javascript in the AJAX content. You cannot initiate new events from within the AJAX content. If your table sorter has an onClick event from the original DOM, then that should work.
Hope this helps
Matt
Matt
Hi there,
I am trying to use this script for an internal intranet system at work that i have been developing. The PHP file the i need to link to, is on a different server than what the main site is running on.
I have tried the following, but cant seem to get it to work? Didnt know if you had any tips/pointers??
$(‘#it-status’).load(‘http://192.168.14.154/vis/newvis/it-status.php’);
Matthew Price Post author
Hi
So you can account for cross domain ajax requests with jQuery’s getJSON and a callback
so the javascript that lives on the domain that displays the response from the php file would have something like this:
the callback at the end of the url here is the key. jQuery generates a random string that you pass to the other domain at the time of the request.
<script>
$.getJSON("http://www.otherdomain.com/file.php?opt_1=xxxx&callback=?", function(data) {
for (i = 0; i < data.length; i++)
{
$("ul#results").append(
"<li><a href='" + data[i].item.title + "' rel="nofollow"></li>"
);
}
});
</script>
here are the contents of the file.php file
// so the var $items here is an array of data that can come from a MySQL db or where ever
foreach ($items as $item) {
$data[] = array ( "item" => array ( "title" => $item['title'] ) );
}
echo $_GET['callback'] . '(' . json_encode($data) . ');';
// remember the callback? so long as you wrap your data in the callback, the other domain will know that the transaction is allowed. afaik, i have yet to see this fail, but i can imagine there are circumstances where it will not.
// insert shameless plug here...this is partially responsible for http://www.wordpressfeeder.com that i built
hope this helps! feel free to reply or contact me directly for more code if necessary
Matt
Evelia
Excellent site. Plenty of useful info here. I’m sending it to a few friends ans also sharing in delicious. And naturally, thanks for your effort! >>> Eliana @
smusharu
thanks a lot, it worked for me. You are an expert
Mina
there are 2 containers in my site, everytime i use your code, it copies the side navigation container and moves the table container. how will i fix that?
Matthew Price Post author
Hi Mina
Can you give me an example link so i can take a look at the source? I am sure that we can solve this
Matt
Peter Drinnan
Finally a straightforward example. Just tried it and it works perfectly. Nice fix for IE.
ibonly
pls i’m trying to test this code offline and downloaded the js script but its not loading anytin.. pls help
Matthew Price Post author
Hi
Are you including jQuery?
What kinds of errors are you seeing if any?
Matt
Mario
Good day, I truly love your example. I need some direction in how to use the setInterval function to call a jquery function:
$(function(){
// Set value
myCounter.incrementTo(x-number);
});
The “x-number” value derives form the php result.
Thank you so very much
Mario
Matthew Price Post author
Hey Mario
Sorry for the delay.
So i think you can do:
setInterval(myCounter.incrementTo(x-number) , 1000);
Lemme know if this is what you mean.
Matt
vicos2
great, but this script to refresh, is there any idea to not refresh?
because when i block some text suddenly the text was unblocked caused by the refresh
Matthew Price Post author
Hi
so you could take this piece out of the setInterval() and it will only load the php contents once
$('#divToRefresh').load('/path/to/your/php/file/userCount.php');
cg
Can u please help in this:
///——————————————–JSP
code:————————— AJAX changeme
///——————————————–JS
code:-pageCount.js————————– windlow.onload =
ajaxFunction; function ajaxFunction(){ var ajaxRequest; // The
variable that makes Ajax possible! var ctx =
“${pageContext.request.contextPath}”; var url = ctx +
“/PageCount?pageName=index”; try{ // Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet
Explorer Browsers try{ ajaxRequest = new
ActiveXObject(“Msxml2.XMLHTTP”); } catch (e) { try{ ajaxRequest =
new ActiveXObject(“Microsoft.XMLHTTP”); } catch (e){ // Something
went wrong alert(“Your browser broke!”); return false; } } }
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //document.myForm.time.value =
ajaxRequest.responseText; var div =
document.getElementById(“page_count”); div.innerHTML =
ajaxRequest.responseText; } }; ajaxRequest.open(“GET”, url, true);
ajaxRequest.send(null); } //————– Problem: div doesn’t
change. I think the request is also not even reaching to my
servlet.
Matthew Price Post author
Hello
So here is the code that i normally use when i do an an ajax request without jQuery
the first bit here is the code that does the lifting
function getXMLHttp() { var xmlHttp; try { xmlHttp = new XMLHttpRequest(); } catch(e) { 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; }And then i use the following to retrieve the response from the php file being used in the ajax request. normally in a click event or a setTimeout()
var unique = Math.floor(Math.random()*999999); // the unique variable makes sure that the browser sees the request as new each time and doesn't cache anything var url = '/path/to/file.php?t=" + unique; xmlHttp = getXMLHttp(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { var response = xmlHttp.responseText; // do some stuff with the response } } xmlHttp.open("GET", url, true); xmlHttp.send(null); return false;Here is a reference URL
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=283
cg
Thank you Matthew. I do not have any click as I am trying
to implement a page counter for the page using AJAX. I was thinking
that once the page is loaded at the end if a request goes to server
and get the page count. Do you suggest to use setTimeout for this
or any other way, as I believe that window.onload is not going to
help, since I couldn’t get it to work as per my need. -cg
Matthew Price Post author
Hello
So are you looking to have this ajax run based on a condition? ie if something happens, then i want to display a page count.
If not, then you can either put the second bit of code in a function like “displayPageCount()” and just run it at the end of your js file, or you can put it in a setTimeout if you want it to display after a certain amount of time.
Matt
cg
No, i want to run it unconditionally each time the page is
visited (to increment the counter in database and show it as page
view count).
Matthew Price Post author
hello
so is there any reason you cannot just put a function in your footer that logs the pageview and then returns and echos the nee count?
do you need it to continually update while a user is on the page to view the number go up while other people are viewing the page?
matt
cg
Sorry, I didnt understand your comment. I have this working
with jsp bean as follows: <jsp:setProperty
property="pageName"
name="pageCountWrapper" value="”
/> But, I want to implement it using ajax. Since page count
is something which most of the users will not interested and only i
will be interested to see how many times page is visited, I thought
to change it using ajax, so that page can be shown to user
instantly and the page increments in parallel.
Matthew Price Post author
ah
so you want to be able to review the page views live from an admin area? or at least a page that the public cannot see?
that being the case, then, yes, you can use ajax to review the page views in real time.
so that being said, what are the errors that you are getting now?
Matt
Matthew Price Post author
you should be able to put the ajax i have above inside of a function in a setInterval()
and watch the page views go up without refreshing the page
cg
It is not admin page. It is regular index page. On the
bottom I want to show the number of times this page is visited. For
that I have already a java class, etc. On calling that code, it
checks the page visited count in database, increment it and then
return that increased page-visited-count, which I want to show. As
I mentioned, I am able to achieve it by instantiating a bean using
jsp bean and then calling the method to get page-view-count. I want
to now change this index page of my site (I mean showing this
page-view-count implementation instead of jsp bean to ajax.). I am
not getting any error. The div tag has value ‘p’, which I want to
change it by getting the value from back-end using ajax. But
nothing happens and page continue to show ‘p’ instead of the
page-view-count. So, I am not sure if ajax (javascript) is getting
executed as expected or not.
Matthew Price Post author
Hi
If you want, you can email me your JS and PHP code and i can take a look at it to see if i see anything wrong. Hopefully we can get this resolved for you : >
Matt
matthew@matthewaprice.com
Ikram
Hi Matt,
I want to make a calendar appointment that have 2 users (A and B). If user A input the appointment, so user B can see it directly without refresh the page. Then I saw your post but, I still didn’t work. I think the problem is in database connection in userCount.php because I’m using a get and post parameter in sql query.
If you want, can I email to you for discuss any further ?
Matthew Price Post author
feel free to email me at: matthew@matthewaprice.com
i have built penny auction sites where the user can see the bids going up while others bid without refreshing the page. so we should be able to get this done
Matt
Sean
Wow!! great post, is there a way to keep changing the
picture, lets say I want to change the picture for each refresh,
how would i do that????? Thanks!!
Matthew Price Post author
Hello
So in your file that is loaded via ajax, you can retrieve a different photo and the setInterval would cause the div with the image to be changed on the fly
You can also have a function that would load a bunch of images when the page loads and store them as a javascript array and then use an image fader pick the images
Hope this helps. If you need anything else do not hesitate to ask.
Matt
Keshav
Man this is super cool.. I was googling around for one of
you are good. I am not well versed in php but
my friend’s request for Gmail auto refresh kind of thing or
facebook auto update kind of thing and stopped on this website.. I
hope this is the idea behind all right? I have never used jQuery or
Ajax but yes sure I am going to try now after this and it will help
my friend as well
yes I will do that in python and use jQuery and AJax I hope it wont
be having any issue. Thanks again