|
|
|
 This tutorial will explain to you the very basics of AJAX, and how to use it to communicate with a MySQL database through PHP.
Ajax stands for Asynchronised Javascript and XML.
Before going on, you should already have a bit...
View Tutorial
|
|
|
|
This tutorial will explain to you the very basics of AJAX, and how to use it to communicate with a MySQL database through PHP.
Ajax stands for Asynchronised Javascript and XML.
Before going on, you should already have a bit of working knowledge on Javascript, PHP and SQL.
Ajax is a web development technique, which utilizes Javascript primarily. This javascript communicates with the server in real time, without needing to refresh the page currently being viewed.
However, javascript works hand in hand with other programming languages. It can be used with PHP and MySQL / XML in a number of different ways.
Lets say you have a web page. Each time the user requests to do something on your webpage, they are redirected. This redirection allows the web server to do something in the background. Whether its to locate a new webpage and display it, or perform a back-end program. However, as much as people are used to this, it isnt very user-friendly. Why? Because it takes time.
Lets introduce Ajax into the picture. With a Ajax based website, the user can click a link, and instantly have a section of the page display new data. This means the whole page doesnt actually have to reload, but only a portion of the page.
Many websites use AJAX very well. Facebook uses AJAX extensivly to update the page in real time, even when the user is away from the computer. Googles 'new' feature, iGoogle also uses ajax. For those unfamilier with iGoogle, check it out here.
It allows users to define how they want to view the page. Modules are loaded onto the page, which the user can drag to other areas, therefore more important or interesting information can be placed where the user wants to see it. Instantly the format is saved, and when the user returns to the page, its already where they want it.
When viewing a non-ajax page, the user is presented with a page of information and links. When the user clicks a link, the server must process this command. The server must check to ensure the page is physically there, return headers and data back to the client, and then the clients machine must process this data into a human-readable web page. During this process, you will see a white web browser while the browser reloads, and the server perform its operations.
In ajax, when a user clicks a link, the web page doesnt need to reload in order to grab the required data. Instead, this is all done behind the scenes. Javascript sends a command to the server which basically says "while this user is viewing this webpage, can you grab this peice of data for me?".
The server then replies with the requested data. Once the javascript has been given this data, it updates a portion of the page instantly without reloading.
Using AJAX to update portions of the page requires you to have a page structure which the javascript can send data to.
Each time you request data, the javascript needs to place it somewhere on the web page. If you want to put the data in the same place each time, you only need one area to display the information.
In addition, you will need something for the user to do in order to request that information. The most common way of doing this is by means of a hyper link.
Once the hyperlink is pressed, the link sends a code to the javascript telling it the user wants this page, go grab it.
The javascript then tells the server, I need this peice of information, please get it.
The server grabs the information and tells the javascript "here it is!".
The javascript then tells the browser, I have some information, it needs to be placed in this area, and the browser updates that area.
When I create updatable areas, I generally use htmls <span> tags. These can be placed where I want the information to be put.
Ok, so I've explained what AJAX is, How its used, and how it works. Lets take a look at the javascript.
You will need to write 3 functions.
grabData() This function will be used to send
grabXmlObject() This function will be used to find out how to call the XML object, depending on the users browser, and whether the browser will accept HTTP requests at all.
postData() This function will be used to find out whether the sever has processed the command send from grabData(), and if it has, post it on the web page.
Lets first look at the grabXmlObject() function.
function grabXmlObject()
{
var objectType;
if(window.XMLHttpRequest)
{
objectType = new XMLHttpRequest();
} else {
if(window.ActiveXObject)
{
objectType = new ActiveXObject("Microsoft.XMLHTTP");
} else {
objectType = null;
}
}
return objectType;
}
Different browsers handle Http requests differently. This function basically determines how to start the Http Request. It will perform 2 if conditions. If the browser successfully creates the http request, it will save the object to the variable objectType.
If the browser can't start the request, it will save `null` to the variable. This function is pretty much standard, so no editing needs to be done to it.
This function is used to send requests to the server.
function grabData(page_identification)
{
xmlHttpObject = grabXmlObject();
if(xmlHttpObject==null)
{
return;
} else {
var requestUrl = "http://www.cybanworld.com/backend.php";
requestUrl += "?page_id="+page_identification;
requestUrl += "&uid="+Math.random();
xmlHttpObject.onreadystatechange = postData;
xmlHttpObject.open("GET",requestUrl,true);
xmlHttpObject.send(null);
}
}
xmlHttpObject = grabXmlObject() - This calls the grabXmlObject function and saves the object returned (if any) as a variable, xmlHttpObject.
The first if condition determines whether the variable is null, meaning no object was created. If this variable is null, it means AJAX cannot be used on the clients browser, and therefore you will need to manually forward the visitor to the requested page.
If the variable is assigned an object, it will go to the next portion of code.
Ajax needs a backend-program to process the data. In this case, I'm using a php program called backend.php. This contains the PHP code which will process the data sent through ajax. It also needs to know what it is getting. Because we want to grab information from a page in the database, we need to provide it with the record Identifier. I usually use unique identification numbers (uid) which is used to make each row in the database unique.
For example:
tbl_pagecontent
uid | page_name | page_content
---------------------------------------------------------
1 | Home | this is the homepage
2 | Tutorials | This is the tutorials homepage
3 | Contact Us | This is where you can contact us
So if i wanted to view the page Contact us, I would send the page_identification number 3.
The next part of the querystring (uid=...) is important. Some browsers cache web pages so they load up faster. This can cause problems with ajax. To cache something means to save information to the visitors computer, just incase they want to view it again. Because you are using the same backend php program to view the data, the computer will display whatever it finds fastest. The UID number is always a random number created by javascript which tells the browser, its a brand new webpage, dont find something from the local cache.
The next part starts with the object xmlHttpObject. This tells the javascript to go to the URL provided. All required data is included in the querystring of the URL. The first line tells the javascript to perform the function postData() once the server has returned the result.
This function asks the server if the request has been processed, and if it has, posts the returned data into a special section of the page. Lets look at the code for this function:
function postData()
{
if (xmlHttpObject.readyState==4)
{
document.getElementById("ajaxInsertArea").innerHTML = xmlHttpObject.responseText;
}
}
The xmlHttpObject.readyState is the objects function to check whether the server has returned the data. If it hasn't, the readyState will not be ==4.
If the readyState is 4, then the response text (xmlHttpObject.responseText will be inserted into the area defined by the document.getElementById() javascript.
Ok, so we've looked at the javascript. This will ask the server to send back the content from the URL provided. So we now need to look at how to process the URL requested.
This file is a PHP file called backend.php.
Ok, so, lets say we click a link. This link sends the page identification number 1 to the javascript. The javascript parses this page_id number into the URL being requested. Therefore, our URL will look something like this:
http://www.cybanworld.com/backend.php?page_id=1&uid=0.23345238
We will use this information, and create a php file to process it as you would normally. Take a look at the PHP file, backend.php:
<?php
//Database connection functions have already been set
$data['page_id'] = mysql_escape_string(strip_tags($_GET['page_id']));
$recordSet = mysql_query("SELECT * FROM tbl_pagecontent WHERE uid={$data['page_id']");
if($recordSet)
{
while($row = mysql_fetch_array($recordSet))
{
$fileData = "<h1>{$row['page_title']}</h1>";
$fileData .= $row['page_content'];
}
} else {
$fileData = "This page could not be found!";
}
mysql_free_result($recordSet);
echo $fileData;
?>
This PHP file processes the data as normal from a querystring. It grabs the page_id variable from the querystring. It formats it for inclusion within a SQL statement. The SQL statement grabs the page_title and page_content from the database, where the uid column = page_id.
If the page is found within the database, it will create the page HTML and store it in a variable ($fileData).
If it cannot be found, it will produce an error message, and save it within the $fileData.
Because this is being processed like a normal page, you don't need to use the return statement, and instead write the variable data to the page using the echo construct.
The server will then send whatever is produced using echo construct and send it back to the javascript function, along with a statement telling the javascript that the server has finished processing the page.
Ok, so, we've created the AJAX javascript. We've created the PHP program used to process and return data back to the javascript.
We now need to create two HTML elements.
One to call the javascript function, and one to receive the returned data.
In this case, I will be using a link to call the javascript AJAX. This is the link HTML I use:
<a href="#" onmousedown="grabData('1')" onkeydown="grabData('1')">Home</a>
When the link is clicked, or a button is used to submit the link, the grabData() function will be called with the page_identification parameter set to '1'.
We now need a section to display the returned data. We will use a <span> html element as a placer. In the postData() function, you will see the data is returned to an element with the ID ajaxInsertArea. So, just create a span element, with the ID ajaxInsertArea:
<span id="ajaxInsertArea"></span>>
Below you will find the entire javascript and HTML.
The HTML page (includes AJAX javascript):
<html>
<head>
<script type="text/javascript">
var xmlHttpObject;
function grabXmlObject()
{
var objectType;
if(window.XMLHttpRequest)
{
objectType = new XMLHttpRequest();
} else {
if(window.ActiveXObject)
{
objectType = new ActiveXObject("Microsoft.XMLHTTP");
} else {
objectType = null;
}
}
return objectType;
}
function grabData(page_identification)
{
xmlHttpObject = grabXmlObject();
if(xmlHttpObject==null)
{
return;
} else {
var requestUrl = "http://www.cybanworld.com/backend.php";
requestUrl += "?page_id="+page_identification;
requestUrl += "&uid="+Math.random();
xmlHttpObject.onreadystatechange = postData;
xmlHttpObject.open("GET",requestUrl,true);
xmlHttpObject.send(null);
}
}
function postData()
{
if (xmlHttpObject.readyState==4)
{
document.getElementById("ajaxInsertArea").innerHTML = xmlHttpObject.responseText;
}
}
</script>
</head>
<body>
<a href="#" onmousedown="grabData('1')">Home Page</a><br />
<span id="ajaxInsertArea"></span>
</body>
</html>
And thats the end of this brief introduction to AJAX. Please note, this is a very basic example of what AJAX can do. It can also be used to create some very advanced applications.
If you would like to learn more about AJAX, I'd suggest looking at the book Ajax, Rich Internet Applications, and Web Development for programmers By Deitel. It has been extremely useful and contains alot more training materials than just AJAX development.
|
 |
|
No comments have been posted!
|
|
Before you can comment, please Register or login.
|
|
|
|