Implementing AJAX

Implementing AJAX

Implementing AJAX is very crucial thing today in web development. AJAX is the abbreviation of Asynchronous JavaScript and XML. In this case, The page of a site have not to be reloaded to communicate with server.

Implementing Ajax can save bandwidth, because, the page only request the needed information to the server. It is very different than a site that fully reloaded to just communicate with the server.

Lets just jump to the JavaScript code.

function ajax()
{
var xmlhttp;
if (window.XMLHttpRequest){//for IE7+, Opera, Chrome, Firefox, Safari
	xmlhttp=new XMLHttpRequest();
}
else{//for IE5, IE6
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
	if (xmlhttp.readyState==4 && xmlhttp.status==200){
		document.getElementById("result").innerHTML=xmlhttp.responseText;
	}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

Then you need to have html code to call the function.

<button type="button" onclick="ajax()">Call Server</button>
<div id="result"></div>

Last but not least, you need the file that will be called by AJAX. In this case I use php file.

echo 'Server say hello to you';

As a result, you will have 2 file in your server.

First is the AJAX file.

<script type="text/javascript">
function ajax()
{
var xmlhttp;
if (window.XMLHttpRequest){//for IE7+, Opera, Chrome, Firefox, Safari
	xmlhttp=new XMLHttpRequest();
}
else{//for IE5, IE6
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
	if (xmlhttp.readyState==4 && xmlhttp.status==200){
		document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
	}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>

<button type="button" onclick="ajax()">Call Server</button>
<div id="myDiv"></div>

Second, the file that will be called.

echo 'Server say hello to you';

Thats all about simple Implementing AJAX. Hope this article of Implementing AJAX, could be useful to you.

http://septiadi.com/2011/04/20/implementing-ajax/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: