Asynchronous JavaScript and XML (AJAX) is a very helpful scripting technique that allows a website or web application to exchange data with a server and update portions of a page without reloading or re-rendering the entire page.
As a result, AJAX can improve site speed and most certainly gives online shoppers a much better ecommerce experience, particularly when sorting or filtering products in a table or when using layered and faceted site navigation.
Many developers have begun to blend AJAX into PHP templates to get great site-wide effects and user experience.
AJAX Benefits
There are at least three benefits to using AJAX, which is not a language itself, but a way to use other languages (JavaScript and XML) together.
Fewer Reloads
AJAX applications should reduce the amount of time your page or application must wait for data to be processed. An AJAX call is much faster than a complete, top-to-bottom page reload. Since page load time and response time are a problem for everyone that wants to provide a good customer experience, using AJAX can often deliver the user experience you want to provide without burdening the browser or the customer's Internet connection.
Imagine, for example, a sortable product comparison table. A shopper is comparing four laptops and first wants to sort by price, then by CPU, then by memory. If a developer had only used PHP and GET or POST commands, the comparison table and, in fact, the entire page would have to be reloaded three times. Certainly, browser caching would have helped, but it would be far better if we could use AJAX to simply adjust the table.
Visitors will surely prefer a retail site where they can easily find and buy everything they need, without spending any additional time waiting for a page to load, and reload, and reload.
Bandwidth Consumption
AJAX may also cut down on the amount of bandwidth—and therefore hosting expenses—that an ecommerce website or application requires. Again, reloading an entire page can consume more bandwidth than using AJAX since in theory the browser will be requesting more information from the web server when reloading an entire page than it would when simply sorting a table or allowing items to be clicked and dragged to a shopping cart.
Again the browser's caching profile will play a role in how much bandwidth using AJAX can save, but every penny saved drops directly to your client's or company's bottom line.
If the site you're developing for has a lot of users, choosing AJAX can reduce the bandwidth usage and expense, since the heavy parts like scripts and images are kept on page.
Better User Interfaces
AJAX is one of the reasons why Gmail, Twitter, Google Analytics, the WordPress admin panel and many other popular web tools and services are so great. The user experience in these applications is, in my opinion, awesome. Think of the way Gmail informs you when you have a new message, without having to reload the page. Or the way that Twitter effortlessly adds tweets to a page, its other scale problems aside. Twitter might be down more often without AJAX and it would almost certainly not be as popular if a user had to click the browser's refresh button every few seconds to see new posts.
AJAX Challenges
Of course, AJAX it is not perfect. It has at least two drawbacks that you should consider.
JavaScript Must Be Enabled
AJAX works only in browsers that support JavaScript and have it enabled. So if JavaScript is disabled in a shopper's browser, the AJAX code won’t be available. There are very few browsers now that don’t have JavaScript enabled by default, but it is still something to be aware of.
SEO and AJAX Don't Necessarily Mix
Generally speaking, AJAX is not good for search engine optimization. Since the content loaded by the AJAX calls appears only when a potential customer or site visitor takes an action, it may not be visible to search engines crawlers.
This is especially true if your AJAX script is introducing new content to the page or application, and not simply reformatting or reorganizing existing page content.
CodeIgniter and AJAX
Now let’s implement AJAX along with some CodeIgniter PHP.
This process is very simple. We will first create a JavaScript file. For this, go to the root of your website project, at the same level with the system folder and create a new folder called scripts. If you are using the .htaccess mod rewrite rule to remove the index.php part of the URL, don’t forget to update it there. Inside the scripts folder, create a file called AJAX.js . We will have three functions in this file:
- getHTTPObject() This will return the XMLHttpRequest Object – we need this to make the asynchronous call.
- doWork() Used to send data to the PHP file.
- setOutput() Will update the page with the results from the PHP file.
function getHTTPObject(){
var xmlhttp;
// Attempt to initialize xmlhttp object
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
// Try to use different activex object
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
// If not initialized, create XMLHttpRequest object
if (!xmlhttp) {
if (typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
else {
alert("This browser does not support AJAX.");
return null;
}
}
return xmlhttp;
}
function doWork () {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("POST", "/test/AJAX_process", true);
httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpObject.setRequestHeader("Connection", "close");
httpObject.onreadystatechange = setOutput;
httpObject.send("name=" + encodeURIComponent(document.myform.name.value));
}
}
function setOutput() {
if (httpObject.readyState == 4) {
if (httpObject.responseText == "") {
document.getElementById('msg').innerHTML = 'The return message is empty';
}
else {
document.getElementById('msg').innerHTML = httpObject.responseText;
}
}
else {
document.getElementById('msg').innerHTML = 'Please wait. Processing';
}
}
<pre>
Let’s analyze the doWork() and setOutput() functions.
**DoWork() :**
- I get the XMLHttpRequest object, to see if I can process the AJAX call.
- If the object is not empty we call the _AJAX_process_ function inside the controller _test_ and we send the name variable as _$_POST_.
- When the script is ready append the result to the _setOutput()_ function.
**setOutput() :**
- There are 5 ready states in AJAX: 0 the request is not initialized, 1 the request has been set up, 2 the request has been sent, 3 the request is in process, 4 the request is complete.
- When the request is complete the function checks to learn if the response is empty. If it is, then show in the `<div id=”msg”></div>` the message "The return message is empty."
- If the message is not empty, show the message received from the controller.
- If the status message is not 4 (complete), then show in the same `<div>` the message "Please wait. Processing."
###The Controller
The controller is very simple. We need just two functions here. The first will load the HTML page and will use the command _$this->load->view();_.
<pre>
<?
function test_AJAX() {
$this->load->view('AJAX');
}
?>
This will load the page AJAX.php inside the application/views folder.
The second function will be named AJAXprocess()_ . I will use it to process the $POST[‘name’]_ variable received via AJAX. This will then check to see if the variable has the value "George" inside the <div id="msg"></div>. If this is the case, it will post the message “You are the script writer.” Otherwise, the message will appear as "The return message is empty."
<?
function AJAX_process() {
if ($_POST['name'] == 'George')
echo 'You are the script writer';
}
?>
The View
In the view, create a form called myform with a variable called name (input type text preferably). Specify it as an attribute of the field onblur="doWork();".
After changing the content of the field and moving outside of it, the AJAX function will be appended.
<div id="msg"></div> <form method="POST" name="myform"> <label for="name">Name</label> <input type="text" name="name" onblur="doWork();"> </form>
That’s all there is to it.
