AJAX example using javascript


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.


Knowledge on JavaScript


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;

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:


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

Send Data to Server

If you need to send information with the GET request:


POST Request

A simple POST request is written as:


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.


Thanks for reading.

Leave a Comment