Friday, June 5, 2009

Introduction to Ajax and sample code for learning Ajax



Ajax stands for asynchronous JavaScript and XML


Ajax is not an Technology in itself. It is a term used for representing the technique used for updating the webpage content asynchronously
without affecting existing content of the webpage.

i-e Some part of the existing webpage on a webbrowser can be refreshed with the content from web server without changing other parts of the webpage i-e without refreshing the whole webpage.

Ajax was made popular by Google by using it in the Google Suggest.

So, basically below steps are involved in using ajax for webdevelopment.

- Creating client side code which will call a javascript function on some events such as onChange.
- Creating a XMLHttpRequest which will be used for sending request to web server from javascript itself and used for receiving response from the webserver.

- A place such as div in the client side code for placing the server response got from the ajax call.

We will see the above steps in detail using below sample code.

Consider below HTML code which will be placed within a Form.


<select name="name" id="name" onChange="showUser(this.value);">


The above code will call a javascript function showUser() when changing the drop-down list value in the Select tag.

The selected value (i-e name in this example) will be passed as argument to the showUser.

The showUser javascript function will look like below mentioned code.



function showUser(str)
{
xmlHttp=GetXmlHttpObject();

if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getuser.php";
url=url+"?q="+str;

url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}



This function creates xmlHttp object by calling a function GetXmlHttpObject()

You can refer the GetXmlHttpObject() below.


function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}


The url to be sent as server request is created by specifying the server-side webpage (e.g getuser.php), the function argument "name", and a random number to avoid cache problem.

A function stateChanged is called on onreadystatechange event for getting the response from the webserver for the request of this created url.

You can refer the sample stateChanged function below.


function stateChanged()
{

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}

else
{

document.getElementById('statusdiv').innerHTML=
"<div align=\"center\" class=\"msg\" ><img src=\"loading.gif\"> Loading ...</div>";
}

}



This function will check the readystate status. If it is complete then webserver response text will be placed inside the client side form, otherwise it will show some loading indication.

Find below the sample server side code (e.g getuser.php) which will be used for sending response according to the value selected in the drop-down list.



<?php
$link=project1_db_connect1();
//for connecting database.
function project1_db_connect1()
{
$link=@mysql_connect("localhost","root","") or exit ();
mysql_select_db ("my_db1") or exit ();

return $link;
}
?>
<table border="1" width="100%">
<tr>
<td>First name</td>
<td>last name</td>
<td>age</td>
</tr>
<?php
$q=$_GET["q"];

$sqluser="select * from persons where id=".$q;
$result=mysql_query($sqluser);
while($userrow=mysql_fetch_assoc($result))
{
$firstname=$userrow['FirstName'];
$lastname=$userrow['LastName'];
$age=$userrow['Age'];

?>
<tr>
<td><?php echo $firstname;?></td>
<td><?php echo $lastname;?></td>
<td><?php echo $age;?></td>
</tr>
<?php
}


?>

</table>


The above code is receiving the selected drop-down value as "q" querystring parameter in the url.

sql query will be used for fetching details such as firstname, lastname age for the corresponding "q" value.

The xmlhttp object is receiving the output of this php page.


More Articles...

No comments:



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: