How to create HTTP GET request in JavaScript?

mahabub.devs3
Mahabubur Rahman
Published on Sep, 20 2024 1 min read 0 comments
image

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();
    xmlHttp.open( "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)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}


 


 


 


 

 

 


0 Comments