This tutorial shows how to create ajax in simple way without using jquery or any other frameworks. It check first browsers and creates an XMLHttpRequest object depending upon the type of browser. Then we can use as per our requirements whether it is a GET or POST request.
Check type of browser and create XMLHttpRequest object

<script type="text/javascript">
var xmlHttp = null;
function getXmlHttpAjax() {
    if (window.XMLHttpRequest) { // for Mozilla, Safari, Chrome etc.
      xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // for IE browser
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    }
    
    return xmlHttp;
}
</script>

 

Suppose

var url="data.php"

 

GET Request Example

A simple GET request can be written as

xmlHttp.open("GET",url,true);
xmlHttp.send();

 

In the above example,
first parameter – type of request
second parameter – url
third parameter – asynchronous or not

The method send() is used to send the data to the server and it is used for only POST request.

In the above example, we may get cached results. So to avoid this we add a unique value to the URL.

xmlHttp.open("GET",url+"?t=" + Math.random(),true);
xmlHttp.send();

 

If we need to send information with the GET request

xmlHttp.open("GET",url+"?id=1234&type=cat",true);
xmlHttp.send();

 

POST Request Example

A simple POST request is written as

xmlHttp.open("POST",url,true);
xmlHttp.send();

 

To POST data, we add an HTTP header with setRequestHeader().
We have to send the data in the send() method.

xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("id=1234&type=cat");

 

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *