AJAX example using javascript

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;



var url="data.php"


GET Request Example

A simple GET request can be written as



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);


If we need to send information with the GET request



POST Request Example

A simple POST request is written as



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



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

AJAX example using javascript

Leave a Reply

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

Scroll to top