user439133
user439133

Reputation: 2143

How to make get requests with JavaScript?

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?

Upvotes: 0

Views: 15033

Answers (3)

Joe.b
Joe.b

Reputation: 542

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");

Upvotes: 2

hemir
hemir

Reputation: 93

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);

Upvotes: 0

frontend_friend
frontend_friend

Reputation: 854

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.

Upvotes: 2

Related Questions