InterviewHubPRO
Section Overview
Q175

Question 175 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

34%
JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

How do you make asynchronous HTTP request

Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the 3rd parameter as true.

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

Today this is considered deprecated, because an async fetch call (in browsers later than 2016) is simpler and more robust.