Working with AJAX
Published: March 5th, 2009 by: Kurtis
AJAX is all over the internet today, and though completely unnecessary, a website with it can function much more quickly. Data can be transferred to and from users efficiently, but a major drawback is the extra code needed and some security issues inherent. Nevertheless, for certain applications, AJAX is great to know and take your project to a new level.
First of all, a soon-to-come feature on JeoReview is on the page where boards can be created. The issue is that there is a chance that someone will pick a board name that is already in use, and while the PHP is set up to catch the error, I would like for JavaScript to be able to handle it earlier and more quickly to prevent posting to pages over and over again. So we will set up the JavaScript much like the examples show:
var xmlHttp; function checkName(name) { var url="checkName.php"; url=url+"?n="+name; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("nStatus").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
I would place this into a separate JavaScript file and link it to the page where the action takes place, but all that is really needed from this point is to add an event trigger to the form field to execute this function. Something like this:
... <input type='text' value='' onchange='checkName(this.value);' /> <p id='nStatus'>Please enter a name for your board.</p> ...
You can see then that the value from the form field will be checked in the function which will send the data to a PHP file which we must now define. Whatever that PHP file “responds” with (or echoes back) will be displayed in the ‘p’ tag we defined below the input field. So let’s finish it off with the PHP file which must check the name entered against the boards already existing in the MySQL database, leading to something like this:
<?php //Connect to MySQL... $name = mysql_real_escape_string($_GET['n']); //We're using the GET method here, but there are applications of POST $getBoards = mysql_query("SELECT `id` FROM `boards` WHERE `name`='$name'"); if (mysql_num_rows($getBoards) == 0) { echo "OK"; } else { echo "Taken"; } ?>
Depending on your application, the echoed strings would be changed and perhaps even a bit more complex, but these work fine for the basic application we worked through.
As I noted above, we used the GET method, just like what is used in normal forms, where variables are passed through the URL to be accessed by the PHP file. However, POST can be used and should be used in certain situations. In general, they coincide with the general rules for form method choosing. GET should be used for shorter requests of one or two variables and POST for multiple fields and especially those sent to the database. Remember that the URL from GET can only be so long before cut off and may not be able to hold all the information from a long request. Therefore, POST is certainly the most viable choice because it can be used in all applications by simply altering the method in the JavaScript and PHP and adding a few lines as noted on the tutorials listed above.
Still wondering where AJAX can come in handy? We’ve all seen those handy “username checks” on registration pages and the suggestions provided by Google, Yahoo!, YouTube, and other big-name websites, and these all employ AJAX. Whether you realized it or not because of their speed, these pages actually utilize more code than a typical PHP/ASP check, but they have certain disadvantages and will always be up for debate.
Matt
Mar 21st, 2009
10:01 pm
In the first code sample, line 13:
if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)
Why are you testing the readyState property for two different values? I’ve never seen that before. Is that for browser compatibility or something else?
Kurtis
Mar 22nd, 2009
6:14 am
You know, I’ve never actually included that when I write code, but according to this discussion it might be necessary. That is pretty outdated though, so I don’t know if it still applies. I just prefer to be safe rather than sorry.