JavaScript

How to send an AJAX HTTP POST request to server

We send an AJAX HTTP request to server using XMLHttpRequest object. The XMLHttpRequest object can be used to send data to a server in scenarios where we want to update parts of a web page, without reloading the whole page.

All modern browsers like Firefox, Chrome, Safari, etc have built-in XMLHttpRequest object. However, some old versions of IE doesn’t support XMLHttpRequest object. If the browser doesn’t support XMLHttpRequest object, we use ActiveXObject to send request to the server.

The following code snippet sends HTTP POST request to server:

    var xmlhttp;
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari support XMLHttpRequest object
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 doesn't support XMLHttpRequest object
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("POST","/servlet/Welcome.do",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("username=tester&password=123");

We use open() and send() methods of the XMLHttpRequest object to send a request to a server.

The above example send POST request to a server. POST is always more secure and robust than GET. Moreover, using POST request you can send a large amount of data because POST doesn’t have any size limitations. However, if you are sending some trivial information to server you can use GET request. Please refer this post to learn how to send GET request to server using AJAX.

Advertisements

One thought on “How to send an AJAX HTTP POST request to server

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s