This tutorial shows an example on AJAX using JavaScript. This will show you how to create ajax in simple way without using jquery or any other frameworks. AJAX is a technique that checks first type of browser and creates an XMLHttpRequest object depending upon the type of browser. Then we can use as per our requirement whether we need to call a GET or POST request.


Knowledge on JavaScript

Example and Source Code

Creating XMLHttpRequest

Here in the below code snippets we will see how to create XMLHttpRequest object through AJAX technique.

As previously mentioned we will use here plain JavaScript technology to create our required object.

The technique will check the type of browser, such as, Internet Explorer, Firefox, Chrome etc. and create an 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;

Usage Example

Here we will see how we can use XMLHttpRequest object to call HTTP GET or POST method.

GET Request

A simple GET request can be written as:"GET",url,true);

In the above example, we see three parameters – GET, url, true.

The first parameter – GET – is the type of request. Generally GET request is used to fetch data from server.

The second parameter – url – indicates the server location, where we want to perform our GET request.

The third parameter – true – indicates the request is Asynchronous. To make it synchronous you can specify as false.

The method send() is used to send the data to the server and sending data in body is required only for POST request.

Avoiding Cache Results

In the above example, we may get cached results. So to avoid this we add a unique value to the URL."GET",url+"?t=" + Math.random(),true);
Sending Data to Server

If we need to send information with the GET request:"GET",url+"?id=1234&type=cat",true);

POST Request

A simple POST request is written as:"POST",url,true);

To POST data, we add an HTTP header with setRequestHeader(). For example, we may set some HTTP headers with the value.

We have to send the data to server location using the send() method."POST",url,true);

Thanks for reading.


Leave a Reply

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