Latest Updates

My Blogger TricksAll Blogger TricksTechtunes

Latest Updates

Thursday, 5 December 2013

What is AJAX ? An Introdution for Beginners

How to develop Web Applications with AJAX 


            AJAX stands for Asynchronous Javascript And XML, although it also works synchronously and without XML, but these to things make a great communication technique that can work on back end without disturbing the whole web Page. Before AJAX the web applications were limited because of the fact that, to retrieve the new data from server the whole page had to be reloaded, it was time consuming and somewhat annoying. There are many websites that wouldn't be working without it, let's take an example of  Facebook the popular social networking site, if a person has a facebook account and he logs in, his time line will be displayed, what if his whole 2-year time line is displayed that will be very resource consuming and buttons on the page end would be annoying. Here comes the AJAX to rescue such that when a user reaches the end of the current page javascript detects it sends a back end server request to retrieve some more data without refreshing the page, serve responds to it and send back the data .....

Now let us see two examples, first with javascript-XML and second with javascript-PHP/MySQL to gt a deep understanding of AJAX applications.



Javascript-XML   :


In this section I will explain how to retrieve a data from an XML file (on server side) using javascript (on client side). XML is a Markup Language that is used to store or transport data. In our case we have an XML file on the serve side with a sample database as shown below :

<?xml version="1.0" encoding="UTF-8"?>
<Book>
  <Title>
    Learn AJAX by example
  </Title>
</Book>

So a bove we have a simple XML file having a parent node named Book and a child node Title. Now lets create a HTML web page on which this data will be displayed :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>What is AJAX ? An Introduction for Beginners - Example</title>
  </head>
<body>
<p> Your Book Title is : </p>
<h1 id="obj" onclick="read('books.xml');"> Book Title will be displayed here 

</body> 

Now Lets create the function read :                      Note: function must be defined before it's called 

  <script type="text/javascript">


function read(file){
  var xmlObj = null;
  if(window.XMLHttpRequest){
      xmlObj = new XMLHttpRequest();  // Should work with most of recent browsers
  } else if(window.ActiveXObject){
      xmlObj = new ActiveXObject("Microsoft.XMLHTTP"); //For old Browsers
  } else {
      return;
  }
  xmlObj.onreadystatechange = function(){
    if(xmlObj.readyState == 4 && xmlObj.status == 200){
       update('obj', xmlObj.responseXML.getElementsByTagName('title')[0].firstChild.title);
     }
    }
    xmlObj.open ('GET', file, true);
    xmlObj.send ('');
  }
  



function update(obj, title){
   document.getElementById(obj).firstChild.title = title;
  }

</script>


So what we did above is that we created two functions one for retrieved data from the serve and other for updating the HTML Tag title.

In the first function first we tried to establish a connection to the server using XMLHttpRequest() class, If its available, then we created an object by instantiationg this class. For older browsers in which it does not work use ActiveXObject("Microsoft.XMLHTTP"). So after we have created the object its time to check whether or nor it's connected to the server, to check this we used an if condition to check its property xmlObj.readyState to be equal to 4 and xmlObj.state to be equal to 200.

An XMLHttpRequest object has a total of 5 states :

0 ⇒ Unitialized
1 ⇒ Loading (Request is initialized)
2 ⇒ Loaded (Server responsed)
3 ⇒ Connected
4 ⇒ Complete

So that's why checked for the state 4 to be completed.
And the xmlObj.state gives different status of the connection, 200 particularly means OK. For more Visit :

http://msdn.microsoft.com/en-us/library/ms767625(v=vs.85).aspx

After all that now it's time to get the data from the XML file, to do this we will use xmlObj.responseXML.getElementsByTagName method, this method takes a node id as a parameter in the XML file. Since we want to extract title  tag we will pass it xmlObj.responseXML.getElementsByTagName('title')[0] ( [0] means first child node).

And at the last we have :

xmlObj.open ('GET', file, true);
xmlObj.send ('');

In this code I have requested to open the connection to the file (variable file) placed in the server using GET method, then I have sent an empty string, this is necessary to complete the connection stages. And the last fuction simply changes the content of the HTML Tag on air.



Javascript-PHP/MySQL   :

In this section we will see how to extract data from a back end database server (PHP/MySQL) with AJAX. 
Lets Consider an example, in this example we have a drop down menu in HTML with employee names, we want that when someone selects an employee from the list it's information should be fetched from the database and displayed in text box below. The HTML for this is :

<html>
<body>
<select name="emp_name" id="emp_name" onchange="get_info($this.value);">
<option>Jim Parker</option>
<option>Miranda jane</option>
<option>Sophie Watson</option>
</select>
<textarea id="info"></textarea>
</body>
</html>

Now we will add a javascript code that will detect the event and send the XMLHttpRequest :

<Script>
function get_info(name)
{
if (name=="")
return;
if(window.XMLHttpRequest)
xmlObj=new XMLHttpRequest();
else if(window.ActiveXObject)
xmlObj=new ActiveXObject("Microsoft.XMLHTTP");
else
return;

xmlObj.onreadystatechange=function()
{
if(xmlObj.readyState==4 && xmlObj.status==200)
document.getElementById('info').innerHTML=xmlObj.resposeText;
}
xmlObj.pen("GET","/search.php?x="+name);
xmlObj.send();
}
</script>

And now the server side we have a PHP file named search.php :

<?php 
$con=mysql_connet("localhost","use","pass");
mysql_select_db($con,"employee_db");
$query = "select * from main where name = '".$_GET['x']."';";
$result=mysql_query($con,$query);
$data=mysql_fetch_row($result);

echo("<h1>".$data."</h1>");
mysql_close($con);
?>

This code gets the name through GET method gets its info from the database and sends it back to the client through XMLHttpRequset object.




For  More Detail On  AJAX-PHP/MySQL  Visit the book :








2 comments:

  1. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information.
    Kik account

    ReplyDelete
  2. AwardSpace is a blazing fast, secure and feature rich web hosting provider. They have all the tools and plugins available on their console which you need to build a website. Hence, it is a complete web hosting package which you can buy during awardspace black friday sale

    ReplyDelete