Jump to content

Ajax auto update a counter from database


chmpdog

Recommended Posts

Hi, I've never really done ajax before. Right now, I'm trying to populate my page with the current number of users that meet a specific sql criteria. Like so:

 

$sql="SELECT * FROM usertable WHERE currentpage = 5";

 

I want this to update as more users enter or leave the page. Is this easy to do? How would I go about doing this, and are there any good tutorials?

 

Link to comment
Share on other sites

Well, as a matter of fact there are a few ways to go about it, lots of tutorials and it is pretty painless.

 

 

If you want to use jQuery:

http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html

 

I just googled for it and that was near the top of my results, but if you are interested in using jQuery that should be something along the lines of what you are looking for.

 

Now, that being said, if for some reason you are trying to avoid jQuery or you want more information about what you are getting into then....

 

Okay so basically, you want a sort of live counter on your page to quantify the number of people currently on the page, right?  If you have continued reading to this point then I'll assume that my google is weak or you have an aversion to doing things the easy way.

 

The end result will be a sort of seemless reload of a small portion of the page whether anything has changed or not because AJAX is client-side and dynamically

makes requests for updates of portions of the page when, or as often as, instructed to do so.  Think of it like this: say you sent me a picture to my cell phone of a puppy or something. Now let's assume that I am actually interested in seeing new pictures when you take them because the puppy or whatever is just so adorable, so every 10 seconds or so I text you and ask for a picture. In this scenario, I am ajax and you are the webserver and the picture(s) are the small part of the page that I keep asking for updates on.  There are alternatives which work that scenario in sort of reverse order and allow you to send me updates rather than me texting you incessantly for updates, but you came for AJAX, so we'll get back on the topic at hand.

 

The gist of the setup is that you'll want to have your page which has the AJAX and nags the server for updates and has an element like a <span> or a <div> to put your counter inside and a page which has nothing except the SQL query and displays the counter that you want to drop into your HTML element.

 

I'll assume that you don't need me to really go over javascript timing functions and just go over the actual AJAX code, but if you need some info on the timing functions then ask google about "setInterval javascript".  I have a sort of cookie cutter function that I typically just tweak from project-to-project, so I'll just briefly go over it and hope your problem is resolved.

function mnuClick(url)
{
	var xmlhttp; /* Establish a variable to reference the fella that will be nag...err...um...making frequent, polite requests for updates from the server on our behalf. */
	var content = document.getElementsByTagName('section')[0]; /* This is just how I found the specific element I wanted to fill with what the ajax is retrieving. */

	/* Now we have to determine if the browser supports XMLHttpRequest() or his mentally challenged little brother the ActiveXObject("Microsoft.XMLHTTP") */
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	/* Now we'll just create a little function that fires when the ready state of our little buddy changes so we can display the stuff we request to the end-user(s). */
	xmlhttp.onreadystatechange=function()
	{
		/* There are several states, but the only one that really matters is 4 which means for better or worse our little buddy is ready to tell us he got what we asked for or so he can tell us to take a long walk on a short pier. */
		if (xmlhttp.readyState==4)
		{
			/* I used a switch here so I could organize various responses and react accordingly. The status is a number and it is either an error number like 404 (File Not Found) or if we are real lucky it is 200 which means we win. */
			switch (xmlhttp.status)
			{
				case 200: /* Everything went well and we are ready to display the update. Just as a note here there is also an xml response if you are pulling down XML, but I've never need it or used it. */
					content.innerHTML = xmlhttp.responseText;
					break;

				case 0: /* I found that when a site doesn't allow remote AJAX (pulling up content in AJAX from a different website) then I get this 0, so I tried to account for it by putting the page in an iframe. It is a dirty fix, but since this wasn't a big major production or anything, just a personal thing for me to use, so I used the quick and dirty fix. */
					content.innerHTML = '<iframe seamless src="' + url + '"><h6>Your browser does not support iframes.</h6></iframe>';
					break;

				default: /* If neither of the events above have taken place then we better throw up an error message. I use a regex to make sure I didn't encounter an error while trying to display an error thereby causing an infinite loop of fail */
					if (url.match(/\/errors\//))
					{
						/* A little console debug message to let the viewer know that I'm a big, lazy dummy and haven't put the appropriate error messages up. */
						console.debug('Error 404 while attempting to show error page: ' + url);
					}
					else
					{
						/* Call this function recursively to display the error page. */
						mnuClick('/errors/' + xmlhttp.status + '.html');
					}
					break;
			}
		}
	}

	/* This last little bit here is what really gets the ball rolling and initiates our request. */
	xmlhttp.open("GET", url, true);
	xmlhttp.send();
}

Hopefully you can decipher my comments (It's really late, I'm really tired and I just added the comments in, so ymmv). The switch case you could swap out for a simple if then to check for status 200 since you aren't actually doing navigation on more substantial areas of the page...yet...Alternatively, you could change the cases or add some new ones to handle things like internal server errors and such.

 

I hope this gets you on the right track and that my sleep deprivation has not resulted in superfluous mindless babbling (well at least not more than usual anyway).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.