Introduction
Asynchronous means that you can make a request to a server and perform other actions while the server is processing your request -- and on the arrival of the response required actions can be performed -- as opposed to conventional web applications, in which the user has to sit back and stare at the blank screen while the server is processing the request. Therefore using AJAX will improve the interactivity of your web application. In conventional web applications when a user makes a request to the server the whole page is reloaded, while AJAX applications only update the relevant portion. Let's look at an example A book shop website is shown in the figure above. To view the books in a specific category, a user selects the category and the related books are shown in the area below. In the conventional web applications the whole page would be reloaded, but in the case of AJAX only the relevant portion is updated (as shown in the figure below). AJAX Architecture AJAX architecture is very simple; a user makes an initial request and, in response, the page with the AJAX engine is loaded. Thereafter, the user sends all requests to the AJAX engine through JavaScript function calls, while the AJAX engine forwards requests to the server, parses the responses, and displays the HTML in the browser. Let's take another look at the book shop example: Normal scenario - When the user selects a particular category the request is sent to the server. In return, a new page with book details is loaded to the browser. AJAX - When a user selects a particular category the AJAX engine is called, which sends the request to the server using XmlHttpRequest object, parses the response, and updates the relevant portion of the page -- therefore the whole page is not reloaded. AJAX engine AJAX engine is nothing but some simple JavaScript functions which use XmlHttpRequest object to make requests to the server. XmlHttpRequest is the main player in an AJAX application it handles all the communication with the server. Common methods and properties of XmlHttpRequest Object
AJAX Explanation Steps Involved
<select onChange="showbooks()" accesskey="cat" size="1" id="category" name="category"> <option value="History">History</option> <option value="Computer Science">Computer Science</option> <option value="Politics">Politics</option> <option value="Commerce">Commerce</option> <option value="Law">Law</option> </select>In the above example I attached a JavaScript function "showbooks" (I will explain it later) with onChange event of dropdown list named category. Whenever a user selects a different option the showbooks() function would be called. This function, basically, is our AJAX engine Showbooks function This function has to perform following tasks
var xmlHttp = false; if (@_jscript_version >= 5) try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } } if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); }Create a reference to XmlHttpRequest Object and assign it to XmlHttp. For MS Internet Explorer 5.0 or above version reference can be obtained by: xmlHttp =ActiveXObject("Msxml2.XMLHTTP ");For other IE versions it can be obtained by: xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");For all other browsers it can be obtained by: xmlHttp = new XMLHttpRequest();Grabbing the selected category: var cat= document.getElementById("category").value;Building the request URL: var url = "getbooks.php?cat=" + escape(cat);escape(cat) is a javascript function, which encodes the string provided as argument. It encodes all that characters which can't be transferred in the request. For example, if a space occurs it is encoded as "%20" because it can't be transferred in the request URL. Making the request: xmlHttp.open("GET", url, true);A connection is opened and the method of connection is specified, i.e. "Get" next argument is the url and last argument specifies the Boolean value, whether you want the request to be asynchronous or not. An event handler is specified, which will fire every time the state of the request object is changed. This event handler is a very good place for error handling, as well as for providing the user with feedback. I will explain the onreadystatechange event later. xmlHttp.send(null);Next the request is made through send() method. The only argument of the send() method is a query string. Since we are using "Get" method we don't need to specify the query string. Parsing the Response function updatepage() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { var response= xmlHttp.responseText; } document.getElementById("detail").innerHtml=response; }readystate=4 means that the server has completed the processing of request and the object is completely intilialized. responseText is the property which represents the server's response. The Last line of the above code updates the relevant portion of the page. We have created the span tag with id details to show the details of the books. More on readystate readystate property can have the following values:
Using these values we can provide user with feed back. Consider the code below function pageUpdate() { if(xmlHttp.readyState == 0) { document.getElementById('details').innerHTML = "Sending Request..."; } if(xmlHttp.readyState == 1) { document.getElementById(' details ').innerHTML = "Loading Response..."; } if(xmlHttp.readyState == 2) { document.getElementById(' details ').innerHTML = "Response Loaded..."; } if(xmlHttp.readyState == 3) { document.getElementById(' details ').innerHTML = "Response Ready..."; } if(xmlHttp.readyState == 4) { document.getElementById(' details ').innerHTML = reponse; } }Putting it all together <script language="javascript"> function showbooks() { var cat= document.getElementById("category").value; var url = "getbooks.php?cat=" + escape(cat); xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = updatePage; xmlHttp.send(null); } function pageUpdate() { if(xmlHttp.readyState == 0) { document.getElementById('details').innerHTML = "Sending Request..."; } if(xmlHttp.readyState == 1) { document.getElementById(' details ').innerHTML = "Loading Response..."; } if(xmlHttp.readyState == 2) { document.getElementById(' details ').innerHTML = "Response Loaded..."; } if(xmlHttp.readyState == 3) { document.getElementById(' details ').innerHTML = "Response Ready..."; } if(xmlHttp.readyState == 4) { document.getElementById(' details ').innerHTML = reponse; } } <script>Server Side Code PHP Developer Print("<table bordercolor='#89A0D6' border='1' cellpadding='0' cellspacing='0 >"); Print(" <tr>"); Print("<td bgcolor='#89A0D6' width='20%'> </td>"); Print("<td bgcolor='#89A0D6' width='20%'><b>Title</b></td>"); Print(" <td bgcolor='#89A0D6' width='20%'><b>Author</b></td>"); Print(" <td bgcolor='#89A0D6' width='20%'><b>Price</b></td>"); Print("<td bgcolor='#89A0D6' width='20%'><b>Add to Cart</b></td>"); Print(" </tr>"); $link=mysql_connect("localhost"); mysql_select_db("ajaxexample"); $query="select * from books where category=cat; $result=mysql_query($query); while($row=mysql_fetch_array($result)) { $title=$row ["title"]; $author=$rowcart["author"]; $price=$row ["price"]; $image=$row ["image"]; print("<tr>""); print("<td bordercolor='#FFFFFF' width='20%'><img src='images/$image' height='50' width='50' /></td>"); print("<td bordercolor='#FFFFFF' width='20%'>$title</td>"); print("<td bordercolor='#FFFFFF' width='20%'>$author</td>"); print("<td bordercolor='#FFFFFF' width='20%'>$price</td>"); print("<td bordercolor='#FFFFFF' width='20%'><a href=addtocart.php?bid=$bid><img src='images/cart.jpg' height='30' width='30' /></a></td>"); print("</tr>"); } } print(" </table>");Positives of using AJAX
Drawbacks of using AJAX
Conclusion AJAX is a great tool for web applications that require a lot of interactivity and user input. Looking at both the strengths and weaknesses of AJAX, however, it becomes clear that there is a trade off Ð the higher the usability for an application's end users, the greater the complexity for an application's developers. For every project, developers should weigh AJAX' pros and cons and consider that trade-off for themselves. |
|