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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Please make an example to illustrate your answer. Welcome to SO.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.