0

My apologies if this is a trivial question but I couldn't find how to make requests using JavaScript.

var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com");
alert(request.status);

I get 0, but http statuses should be between 100 and 600. Where am I going wrong?

user439133
  • 1,943
  • 3
  • 12
  • 5
  • Possible duplicate of [HTTP GET request in JavaScript?](https://stackoverflow.com/questions/247483/http-get-request-in-javascript) – saurabheights Sep 20 '19 at 16:47

3 Answers3

2

The issue is that you're never making the request. See an example of XMLHttpRequest here.

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "http://www.google.com", true);
oReq.send();

Notice oReq.send(), which sends the request. Also notice the reqListener function, which gets called when the request completes.

frontend_friend
  • 587
  • 6
  • 9
2

Check the article How to get the response of XMLHttpRequest

In a nutshell, XMLHttpRequest is asynchronous by default, so you need to register a callback function on the onreadystate.

var request = new XMLHttpRequest();
request.onreadystatechange=function(){
  if (request.readyState==4 && request.status==200){
    alert(request.status);
    // To get the response use request.responseText;
  }
}
request.open("GET", "http://www.google.com");
request.send(null);

Note that for older versions of IE (IE5 and IE6), you need to get the request from an ActiveX Object as follows:

variable=new ActiveXObject("Microsoft.XMLHTTP");
Community
  • 1
  • 1
Joe.b
  • 422
  • 1
  • 6
  • 16
0

I'm not sure but you just define your request. Did you forget to send it ?

Try

var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com");
request.send(null);
alert(request.status);
hemir
  • 93
  • 1
  • 1
  • 6