December 11, 2009

PHP AJAX simple example

Today I'll write simple AJAX (Asynchronous JavaScript And XML) program using PHP language.
In this example, you will be able to display user a Welcome Message without refreshing the webpage.
The webpage have one Name textbox and a command button. When user enter his name in textbox and press the Hola button, it will display 'Hola User!' message.

If the name textbox is left blank, it will display message 'Hola Guest!'.

Here is the home.html code.


<html>
<head>
<script type="text/javascript" src="simple.js"></script>
</head>
<body>
Name: <input type="text" id="txtName"/>
<input type="button" id="btnHola" value="Hola" onClick="HolaMe(txtName.value)"></input
<p><span id="txtMsg"></span></p>
</body>
</html>

This html file need simple.js javascript file to process your request asynchronously. The simple.js file looks like below

var xmlhttp;
function HolaMe(str)
{
if(str.length==0)
{
document.getElementById("txtMsg").innerHTML="Hola Guest!";
return;
}
xmlhttp=GetXmlHttpObject();
if(xmlhttp==null)
{
alert("Your browser don't support XMLHTTP!");
return;
}
var url="hola.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=showHolaMsg;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function showHolaMsg()
{
if(xmlhttp.readyState==4)
{
document.getElementById("txtMsg").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

This javascript check if the textbox is empty it displays 'Hola Guest!' message. Otherwise it sends the user name to hola.php file.

The hola.php file is very simple. It just echo the formatted response.

<?php
$q=$_GET["q"];
$response="Hola ".$q."!";
echo $response;
?>

No comments: