AJAX is Asynchronous JavaScript And XML. Jesse James Garett coined term AJAX in his article: “AJAX : A new approach for a new application”. This term used in 2005, where as technologies existed earlier. Ajax is just a new style of designing application. You can Manipulate GUI elements using Ajax. While using Ajax, you will not see any flicker when you perform some event on a web page. The reason is that an Ajax enabled page is not submitted back to the server. In fact only a portion of that page is submitted to the server using XMLHttpRequest object of JavaScript. As soon as the response is received from the server by XMLHttpResponse object it is updated on the web page. So you feel a smooth desktop like performance of web applications.

AJAX Technologies

  • HTML (or XHTML) and CSS for Presenting information
  • DOM – Document Object Model for dynamic display and interaction with the information
  • XML, XSLT (Optional) for data interchange and manipulation
  • XMLHttpRequest for asynchronous data retrieval object
  • All run in JavaScript

Uses of Ajax Paradigm

  • Real-Time Form Data Validation – Form data that require server-side validation can be validated in a form “before” the user submits it.
  • Auto completion – A specific portion of form data may be auto-completed as the user types.
  • Master Details Operations – Based on a client event, an HTML page can fetch more detailed information on data without refreshing the page.
  • Sophisticated UI Controls – Controls such as tree controls, menus, and progress bars may be provided without page refreshes.
  • Making Web apps like desktop apps – User interaction should not stop and making the browser a thicker client
Source: http://adaptivepath.com/publications/essays/archives/000385.php

XMLHttpRequest

Keystone of Ajax is XMLHttpRequest object. XMLHttpRequest is an object of JavaScript and it is client-side component. It creates HTTP requests (both GET and POST) without blocking the user. It was first introduced in MS Internet Explorer 5. Being standardized by W3C, it is now widely supported in most of the browsers e.g. Mozilla Firefox, Safari 1.2, Opera 7.6. It can be used to request or send any kind of data.

Example using XMLHttpRequest – Step 1

First Browser specific object creation. Yes, you need to take care for which browser you are creating the AJAX. But thank God, it is not much of pain as there are only two versions of the object i.e. IE (internet explorer) and Non-IE

Example

  • var req = new XMLHttpRequest(); // Non-IE
  • var req = new ActiveXObject(“Microsoft.XMLHTTP”);  // IE

Example using XMLHttpRequest – Step 2

Next you need to transferring data to Server. You can do this by openning connection and sending the data to the server. open() is used to initialize connection to Server while send() to send the actual Data.

Example

  • req.open(“POST”, “phone.php”)
  • req.send(“name=Timmy&city=Boston”)

XMLHttpRequest contacts the server and retrieves the data. It can take indeterminate amount of time. Event Listener determines when the object has finished retrieving data. “readyState” variable of XMLHttpRequest object lets you know what is the state of your request. State could be:

  • 0 – Un-initialized
  • 1 – Loading
  • 2 – Loaded
  • 3 – Interactive
  • 4 – Completed

You can check state as follows:

if(req.readyState == 4)
{
if (req.status == 200)
  {                        //200 means OK (no error)
success();
  }
}

Ajax Example – 1

This example demonstrates a dropdown that allows you to select a category of your contact group. It lists your contacts from your selected category on the page using AJAX. Important thing to notice here is that you won’t see the page to be submitted back to the server. Everything just happens in a flash just like desktop applications.

HTML Code

<body>
<form>
Select a User:
<select name="users" onChange="showUser(this.value)">
<option value="0">Select Contact Group</option>
<option value="1">Friends</option>
<option value="2">Family</option>
<option value="3">Classfellows</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>

Javascript Code

var xmlhttp;
function showUser(str)
{
	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
  	{
  	alert ("Browser does not support HTTP Request");
  		return;
  	}
var url="getuser.php" + "?q=" + str;
xmlhttp.open("GET",url,true);
xmlhttp.send();
xmlhttp.onreadystatechange=stateChanged;
}
function stateChanged()
{
	if (xmlhttp.readyState==4)
	document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
function GetXmlHttpObject()
{
	// code for IE7+, Firefox, Chrome, Opera, Safar
	if (window.XMLHttpRequest)
  	  	return new XMLHttpRequest();
  	// code for IE6, IE5
	if (window.ActiveXObject)
  	 return new ActiveXObject("Microsoft.XMLHTTP");
return null;
}

PHP Code

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
mysql_select_db("addressbook", $con);
$sql="SELECT * FROM contacts WHERE groupid = ' ".$q."‘ ";
$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>E-mail</th>
</tr>";
while($row = mysql_fetch_array($result))
{
  echo "<tr>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['city'] . "</td>";
  echo "<td>" . $row['email'] . "</td>";
//  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>

If you find any trouble in running this code. Just post me comment :-)

Where has AJAX been used?

  • Google Maps – http://maps.google.com
  • Google Suggest – http://www.google.com/webhp?complete=1&hl=en
  • GMail
  • Flickr
  • and many other…

Essential Reading

http://adaptivepath.com/publications/essays/archives/000385.php
http://en.wikipedia.org/wiki/Ajax_(programming)
http://www.ajaxpatterns.org
http://w3schools.com/ajax/
 
 

 Go To >> Lecture 1. PHP Basics

Tagged with: PHP
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.