How to create HTTP GET request in JavaScript?

Mahabubur Rahman

Browser provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript. You can create a function as following - 

function httpGet(theUrl)
    var xmlHttp = new XMLHttpRequest(); "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;

However, synchronous requests are discouraged and will show a warning along its line.

You should make an asynchronous request and handle the response in an event handler. So the code will as bellow - 

function httpGetAsync(theUrl, callback)
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
    }"GET", theUrl, true); // true for asynchronous 

Post a Comment

Post a Comment (0)