How to implement AJAX using JavaScript? – JavaScript AJAX Example

As we know Ajax (Asynchronous JavaScript and XML) is a technology to implement partial loading. The idea is in place of sending request to load whole the page from server we can fetch the line of changes we required in our page. This process helps to reduces network load. The result we have better performance & faster web.

Today we have many ready-made libraries are available to make an Ajax Call easier & programmer friendly. But as a core engineer it is required to know what is the basics of an Ajax Call. That’s why I am presenting this topic here. It is also very useful for fresher.

In the below example I am implementing JavaScript AJAX Example, no third-party libraries I used here. Ajax-Demo.html is the file where from I am doing an Ajax Call to Demo-Ajax.txt file to fetch its text contents. To do so on button click I am calling a function demoAjaxCall(). In side this function I created an instance xmlhttpObj for the XMLHttpRequest object. Then using open method I am instructing xmlhttpObj to locate the demo-ajax.txt file. Here in xmlhttpObj.open I am using get method. Finally using send method I am sending request to the server.

Later in xmlhttpObj.onreadystatechange() I am checking readyState & status. If readyState is equal to 4 & status is equal to 200, it mean my Ajax Call is successful. To display the response from Ajax Call here I used xmlhttpObj.responseText to the inner html of the div demoAjax.

JavaScript-AJAX-Example.html

<!DOCTYPE html>
<html>
<head>
<title>JavaScript AJAX Example</title>
<script type="text/javascript">
function demoAjaxCall()
{
var xmlhttpObj;
if (window.XMLHttpRequest)
{
/* Compatiable for IE7+, Mozilla Firefox, Google Chrome, Opera &amp; Safari */
xmlhttpObj=new XMLHttpRequest();
}

xmlhttpObj.onreadystatechange=function()
{
if (xmlhttpObj.readyState==4 &amp;&amp; xmlhttpObj.status==200)
{
document.getElementById("demoAjax").innerHTML='<h2>' + xmlhttpObj.responseText + '</h2>';
}
}
xmlhttpObj.open("GET","demo-ajax.txt",true);
xmlhttpObj.send();
}
</script>
</head>
<body>

<div id="demoAjax"><h2>On below button click this label will show you text from demo-ajax.txt using Ajax Call</h2></div>
<button type="button" onclick="demoAjaxCall()">Trigger an Ajax Call</button>

</body>
</html>

Demo-Ajax.txt

This is the text from demo-ajax.txt file. Your Ajax Call is Successful.