JS Coding Questions Logo
JS Coding Questions
#171💼 Interview💻 Code

How do you make asynchronous HTTP request

Advertisement

728x90

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

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

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

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 86

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
171of476