JavaScript

How to send an AJAX HTTP GET 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 GET 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("GET","/servlet/Welcome.do?firstName=Devesh&lastName=Sharma",true);
    xmlhttp.send();

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

The above example send GET request to a server. GET is always simpler and faster than POST. However, there may be instances where you may want to use POST request:

1. Use POST request when you are sending a large amount of data because POST doesn’t have any size limitations.
2. Use POST request when you are sending sensitive information like username and password because POST is more secure and robust than GET.

Please refer this post to learn how to send POST request to server using AJAX.

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

Leave a comment