Asynchronous JavaScript and XML or AJAX in brief, is a method we use to access data from server asynchronously, utilize JavaScript object, XMLHttpRequest. It called asynchronous because we in client-side, don’t have to refresh the page when do request to the server, make the web page more interactive, dynamic and faster than old way we create a web page.
So how we can use it? The example below needs a server to try, you can use XAMPP or your web-server to give it a try. Create an Ajax Script first, I put it in head tag.
<html>
<head>
<script language="javascript" type="text/javascript">
num=1;
function ajaxFunction(){
// Create an AJAX variable, name doesn't have to be same
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
// Error from browser
alert("ERROR: Reinstall your browser.");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
// ready state = 4, the request has been processed, ready to get the data
if (ajaxRequest.readyState == 4)
{
//we put the data requested to id = idn in your page
document.getElementById("idn").innerHTML = ajaxRequest.responseText;
}
}
// we send a variable to server , a var variable is filled with num value
ajaxRequest.open("GET", "a.php?var="+num, true);
ajaxRequest.send(null);
num = num + 1;
if (num == 5)
num = 1;
}
</script>
</head>
How we call the function? Just create a button or something to trigger the function. For example when we press a button in that page.
<body> <input type="button" value="press" onclick="ajaxFunction()" /> <br/> <div id="idn"> This is where the request will be placed. </div> </body </html>
I’ve mentioned php file “a.php” to receive the request, then we should create a php file with same filename mentioned above.
<?
echo $_GET['var'];
if ($_GET['var'] == 1)
echo "hahaha";
else if ($_GET['var'] == 2)
echo "hihihi";
else if ($_GET['var'] == 3)
echo "huhuhu";
else if ($_GET['var'] == 4)
echo "hehehe";
else if ($_GET['var'] == 5)
echo "hohoho";
?>
The output is depend on how many times you click the button. The first time you click the button, it should say “hahaha”, because the initial value of num variable is 1. However, if var value is 5, it will reset to 1 after the server processed the request, so the “hohoho” will never showed up.
Popularity: 3% [?]





