If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!
22 Jul
Posted by ProCOM
on July 22, 2007 – 12:48 am - 1,445 views
With the recent popularization of AJAX (Asynchronus Javascript And XML), it is now unnessecary to reload a page with the same basic layout, just to get new content. You can use AJAX to retrieve just the content without reloading the page, then change the value of a content area.
First of all, to use AJAX you must understand how it works. AJAX is JavaScript that can run through the “AJAX Engine” and by doing so, retrieve data from a remote page through HTTP, without having a page reload. It is similar to PHP’s file_get_contents(), however it can be done through JavaScript as a client-side script.
The first thing we need, is a php file that we will call with AJAX. It doesn’t have to be PHP, but since it is the most popular server-side language, that is what we’ll use. If you have decent knowledge of another language you would like to use instead, I’m sure you could translate the code. In this file, we will use a GET variable to determine the MySQL query we need to perform. We are using GET because it is accessible by AJAX. The great thing about it is that the file you are calling can be incredibly simple, and just be straight textual information. Here is an example:
<?php
//This file is text.php
mysql_connect(“localhost”, “username”, “password”); //Connect to the mysql server with your host (most likely localhost), username, and password
mysql_select_db(“db_name”); //Select your database by name
$page = $_GET[“page”]; //This is the variable we retrieve through GET to know which row of content to retrieve
$sql = “SELECT * FROM pages WHERE page = ‘$page’”; //This is the text of the query. We will select the content field from the table ‘pages’ where the page field has the same value as the one we want to retrieve
$query = mysql_query($sql) or die(mysql_error()); //Make the actual query
if( mysql_num_rows($query) == 1 ) //Check to see if we found 1 row with that page name
{
$r=mysql_fetch_assoc($query); //Set a mysql fetching variable for the query
echo $r[“content”]; //Echo out the content of the page we want
}
else
{
echo “Sorry, that page was not found.”; //Otherwise, echo out an error message saying the page was not found
}
?>
Now we have a file that will take in a page name through GET, query a row from our database with the same page name as that, then if that row exists, echo out the content of the page. We need a table in a database for this to work, however, so here is a very simple query to create a table with a field for page name and a field for content:
CREATE TABLE `pages` (
`page` VARCHAR( 255 ) NOT NULL ,
`content` TEXT NOT NULL
)
Next we need to create the AJAX function to call that file. I’ll start by posting the code then explain it:
function getPage(page){
var xmlhttp=false; //Clear our fetching variable
try {
xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’); //Try the first kind of active x object…
} catch (e) {
try {
xmlhttp = new
ActiveXObject(‘Microsoft.XMLHTTP’); //Try the second kind of active x object
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=‘undefined’) {
xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
}
var file = ‘text.php?page=’; //This is the path to the file we just finished making *
xmlhttp.open(‘GET’, file + page, true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
var content = xmlhttp.responseText; //The content data which has been retrieved ***
if( content ){ //Make sure there is something in the content variable
document.getElementById(‘content’).innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
}
}
}
xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
You make have noticed that there are 4 lines of code that I placed asterisks by. I did that because I wanted to further explain them and tell you why they could be different for something else you might do with AJAX.
*
var file = ‘text.php?page=’; //This is the path to the file we just finished making *
The reason I starred this is becaused I didn’t have enough space to explain it in the comment. What you would have in this variable is your file (text.php in this instance) but with a blank form of your GET variable attached (page=) and of course you need the question mark (?) inbetween to separate the file extension from the GET variable. The reason we have a blank GET variable at the end is because in the next line we add the page title on to the end of it.
**
xmlhttp.open(‘GET’, file + page, true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
I actually already explained why I starred this line. This first declares we’re retrieving data through GET, then we have our file variable (see *) followed by the page title. What this would look like if we weren’t using variables would be something like: text.php?page=home (pretending that home is the name of the page we want to retrieve).
***
var content = xmlhttp.responseText; //The content data which has been retrieved ***
I just starred this to make sure it was understood that we are merely putting the response text from the XMLHttpRequest into the variable content so it’s easier to work with. You don’t have to name it content, however if you change it make sure you change all of the other places where it is used also.
****
document.getElementById(‘content’).innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
Currently what this line does is it changes the inner content of your div to the newly retrieved content. In this case we are using a div with the id ‘content’. If you have basic knowledge of JavaScript, you could do whatever you wanted with the content by now. For this tutorial I wanted to put the content into a div, but you could do with it what you like!
What I’m going to do now is put up an example html page (we’ll call that index.html) with the JavaScript AJAX functions embedded in it and two divs (one for content and another for a couple of example links).
<!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”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1″ />
<title>Our wonderful AJAX page!</title>
<script language=“javascript” type=“text/javascript”>
function getPage(page){
var xmlhttp=false; //Clear our fetching variable
try {
xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’); //Try the first kind of active x object…
} catch (e) {
try {
xmlhttp = new
ActiveXObject(‘Microsoft.XMLHTTP’); //Try the second kind of active x object
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=‘undefined’) {
xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
}
var file = ‘text.php?page=’; //This is the path to the file we just finished making *
xmlhttp.open(‘GET’, file + page, true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
var content = xmlhttp.responseText; //The content data which has been retrieved ***
if( content ){ //Make sure there is something in the content variable
document.getElementById(‘content’).innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
}
}
}
xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
</script>
</head>
<body>
<div id=“links”>
<a href=“javascript:getPage(’home’)”>Home</a> <a href=“javascript:getPage(’page2′)”>Page 2</a>
</div>
<div id=“content”>
</div>
</body>
</html>
And there you have it, you’ve now got everything you need to make a simple page system using AJAX, PHP and MySQL. Just as a note, you’ll need to actually create rows in your table with page names home and page2 for this to work
Those are just examples though so you can use them as a model for other links.
Quite possibly one of the most important things you need to keep in mind when working on a larger coding project is to stay organized. Organization can either make or break your project, so I’ve decided to share a few tips I use to try and keep organized.
Indentation
Although to many it is an obvious thing to do, there is far too much code out there that doesn’t use indentation at all or correctly. It is very easy to make a long script in notepad with absolutely no indentation, however, one of the most common mistakes you can make while coding is forgetting to close a brace (curly bracket; { }), and this is only made easier by not indenting your code. Indenting allows you to see all the layers in your code much more easily, producing much nicer looking code, not to mention being a lot easier to read.
Here is an example of how you can best use indentation in your code
statement ( condition )
{
//One indentation in
statement ( condition )
{
//Two indentations in
}//Close a layer
statement ( condition )
{
//Into another layer
}//Close it
}//Close the original layer
Commenting
Another very important habit you should have with your coding is always commenting what you’re doing. It helps you find where something occurs in the script, why that might be occurring, as well as telling anyone else reading your script what you were trying to accomplish. This makes it easier to debug things, as well as get help with your scripts. I generally comment to signify new sections of code, what some more confusing functions are doing, what variables are for, etc.
Variable names
It is also very important that your variables are well named. Knowing how to name variables descriptively yet in just a few characters is a very great skill to have in my opinion, and is unfortunately one I’m not the greatest at (ha ha). You want to be able to communicate to whoever is reading the script what that variable does as well as anything else you want associated to it such as the data type (int, txt, etc.), or some other classification you deem useful for your particular script. I also find it very helpful to capitalize separate words or abbreviations in your variable names (or any other names for that matter) to give you results like intYear or txtMessage.
Arrays are your friend!
This is almost a continuation of the variables section, however I thought it was important enough to have it’s own section. Arrays are not only for storing common array data such as rows of a table. They can be used to your advantage for common use variables that you want to be associated in some way. You could use it the same way as variables by storing more information in just the name. Say for example you had some key numerical values that were used throughout your script; you could use the array num[] or whatever you want then store your data in parts of the array: num[’varKey’] = 129837981. It also lets you classify your variables in a little more detail so you could have the same name for more than one value like: my[’name’] and your[’name’].
Follow some sort of protocol
In general your script should all be structured similarly. You should have a set method for most things like where you put your comments, (above, after, before, below, whatever you want), how far you indent (tabs or a number of spaces), how you put your braces for statements (same line or next line usually), and any other little thing that you probably do habitually anyway without noticing it. Whatever you do though, you should keep it all the same so you can keep everything looking neat and tidy!