Ajax basic sample program

What is Ajax??

AJAX = Asynchronous JavaScript and XML.

AJAX is not a new programming language, but a new way to use existing standards.

AJAX is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page.

Basic sample exercise program to test how ajax works??

Create two php pages like baseball.php and testajax.php

Scenario: This scenario is very simple to understand how ajax works without reloading the whole page to change the content. Now we have some data in baseball.php, without executing baseball.php directly we will get baseball content on testajax.php by just calling with ajax commands..

Baseball.php

<html>
<body>
Scores Board:
<br/>
England : 1-2
samron:23
greenord: 35
<br/>
Australia : 2-2

sofry: 43
dremat: 32
<br/>
</body>
</html>

testajax.php

<html>
<head>
<script language=”javascript” type=”text/javascript”>

xmlhttp = new XMLHttpRequest();

function getscores(){

xmlhttp.onreadystatechange =

function(){

/*
0 : have not started
1: Connected to server
2: Server has received our request
3: Server Processing
4: Request is finish and data is received
*/

if(xmlhttp.readyState == 4 && xmlhttp.status==200)
{
document.getElementById(‘scores’).innerHTML = xmlhttp.responseText;
}
else
{
document.getElementById(‘scores’).innerHTML = “Waiting for server response..”;
}

}
xmlhttp.open(“GET”,”http://localhost:82/baseball.php&#8221;,true);
xmlhttp.send();
}

</script>
</head>
<body>
<div id=”scores”>

<div><br/><br/><br/><br/>
<br/><input type=”button” value=”Get Scores!!” onclick=”getscores()”/>
</body>

</html>

Now just execute testajax.php in your wamp/xampp server to see the baseball.php content in testajax page..very simple right 😉

Advertisements