AJAX for idiots.
April 5, 2006 3:54 PM   Subscribe

Stupid web development question about updating a database on a mouse click without re-loading the page (AJAX required?)

I've taken it upon myself to learn PHP and MySQL for a very basic website I want to build. Basically, I have a database with a bunch of text entries and I want the site to dump them out based on various sorting or restrictions. Simple enough.

The part I need help with is that I want to give users a way to "rate" each item, so next to each line in the list there is a little thumbs up icon or star or something. I need a way for a user to click on the icon and have it update the "score" of that icon in the MySQL DB without refreshing the page or taking them to a different page. This is probably pretty simple to do, but I don't really know where to begin...Can I do this with pure JavaScript? Any good code templates for this sort of thing? Do I have to learn AJAX-y techniques?

As an example, think about the gMail "star" thing. When you click on the star, it fills in, and nothing else happens. More importantly, that message gets permanently marked as starred. That's what I want to happen!
posted by TunnelArmr to Computers & Internet (13 answers total) 1 user marked this as a favorite
Thinking out loud here....... You can store the data using Javascript and then have it processed onUnLoad. So it's going to another page to process, but that's transparent to the user.
posted by y6y6y6 at 3:59 PM on April 5, 2006

AJAX is a perfectly decent solution, if you want to go that route.
You could also bury a little form with a post in little IFrames, for each rating element. The post would happen inside the IFrame, but the outer window would stay the same.
posted by frufry at 4:09 PM on April 5, 2006

It certainly is possible to do it via the temporary JavaScript storage and the onUnload() handler, but Google is probably doing it via AJAX. Don't make me look at their code, please!

AJAX is very simple in principle.

It's just like every other request to a server, except that as you say, the user doesn't see it happen. The request goes to a server, the server replies with some XML, and you process the XML.

In your case you'd make an "update my database with this score for this user and this item" request, via a javascript: URL or an onClick event, and the server would reply, if all went well, with some minimal XML that would mean "it worked" ... or something would go wrong in which case you'd have to handle the error, of course.

There's a little demonstration of how XHTTPRequests are used with iTunes here that might give you a start.
posted by AmbroseChapel at 4:11 PM on April 5, 2006

Response by poster: The reason I'm concerned about doing it with AJAX is that I know nothing about it, and from the limited info I have seen, it would be a lot to learn for one minor function.

y6y6y6, that Javascript solution would be nice, but won't it then not be recorded if they close the browser window straightaway instead of continuing on to another page?
posted by TunnelArmr at 4:12 PM on April 5, 2006

You can play around with this one or this one and see how they work.

Ajax is a bit of an advanced topic if you're just learning PHP, though.
posted by jellicle at 4:14 PM on April 5, 2006

You don't need to learn the details of XMLHttpRequest if you use either the Dojo or the Prototype Javascript libraries.
posted by nicwolff at 4:31 PM on April 5, 2006

I second the Prototype Library. After using it to design a number of small interactive web apps, It makes Ajax as simple as calling the functions of a pre-created Ajax object. Very simple, very easy on the individual who wants none of the nitty gritty.
posted by potch at 4:38 PM on April 5, 2006

no need to go Ajax... use javascript to asynchronously load an image where the URL of the image is the vote-processing (or whatever) script...
(as posted in a recent AskMefi answer )
posted by nielm at 4:40 PM on April 5, 2006

Ajax isn't nearly as scary as you might think... check out the 30 Second AJAX Tutorial by Rasmus Leidorf, creator of PHP. He lays it out in a very, very simple way.
posted by ph00dz at 4:56 PM on April 5, 2006

AJAX sounds like what you want. If you're worried about things being too complicated, it don't get much simpler than XHConn.
posted by the jam at 9:09 PM on April 5, 2006

Here's the basics (all snippets, but should be enough to get you started):

Stars (right-click, save-as), or make your own:
off: on:

Code Snippets:
function updateStar(id) {
   var imgsrc = (document.getElementById(id).src == "star_off.gif") ? "star_on.gif" : "star_off.gif";
   var sendId = id.split('_')[1];
   var sendStar = (imgsrc == "star_off.gif") ? false : true;
   var objXml = new XMLHttpRequest();
   var datasource = "changestar.php";
   var params = "id=" + sendId + "&star=" + sendStar;
   objXml.open("GET", datasource + "?" + params, true);
   objXml.onreadystatechange=function() {
      if ((objXml.readyState==4) && (objXml.status==200)) {
         alert('status changed.');
   <tr><td>Atom Heart Mother</td><td><img id="album_24123" src="star_off.gif" onclick="updateStar(this.id)"></td></tr>
   <tr><td>Dark Side of the Moon</td><td><img id="album_42312" src="star_off.gif" onclick="updateStar(this.id)"></td></tr>
   <tr><td>Wish You Were Here</td><td><img id="album_13534" src="star_off.gif" onclick="updateStar(this.id)"></td></tr>
   <tr><td>The Wall</td><td><img id="album_82322" src="star_off.gif" onclick="updateStar(this.id)"></td></tr>
posted by Civil_Disobedient at 10:19 PM on April 5, 2006

Forgot to mention:

In the above code, the script "changestar.php" takes two arguments: the first is the ID of the album to change, the second is the "starred" status (true/false).

So, for example, the script could generate an SQL query like this:

idFromGET = (retrieve the id variable in the GET variables)
starFromGET = (retrieve the starred status from the GET variables)

String sqlquery = "UPDATE table_albums SET col_star =" + starFromGET + " WHERE col_id = " + idFromGET;

Naturally, if something like this is exposed to the "masses" (i.e., it's on the internet) you'd want to validate the shit out of any GET variables before creating a query string out of them.

If any or all of this is over your head, let me know and I'll try and help.
posted by Civil_Disobedient at 10:27 PM on April 5, 2006

I've spent the entire day evaluating the different AJAX libraries for PHP, and xajax seems the best (supports Unicode, actively developed, full featured, well documented, simple to use, developer community, works with all major browsers). TinyAjax is also a worthy alternative, but not as good IMHO.
posted by Sharcho at 3:13 AM on April 6, 2006

« Older Source of spares for old laptops?   |   Looking for best 'get me up to speed' resources... Newer »
This thread is closed to new comments.