AJAX example using javascript

Introduction

This tutorial shows an example on AJAX using JavaScript. Here I will show you how to use AJAX technique in simple way without using jquery or any other framework. AJAX is a technique that checks the type of browser and creates an XMLHttpRequest object depending upon the type of browser. Then you can a GET or a POST request.

Prerequisites

Knowledge on JavaScript

XMLHttpRequest

Here in the below code snippets I will show you how to create XMLHttpRequest object through AJAX technique.

As previously mentioned I will use here plain JavaScript technology to create the 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;
	}
</script>

Usage Example

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

GET Request

A simple GET request can be written as:

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

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.

Avoid Caching Results

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

Send Data to Server

If you need to send information with the GET request:

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

POST Request

A simple POST request is written as:

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

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

You have to send the data to server location using 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 reading.

Related posts

Leave a Comment