3

How to get HTTP status code of another site with JavaScript?

3
  • 1
    How are you fetching the content? Some code would help. Commented Jul 21, 2010 at 11:35
  • stackoverflow.com/questions/837064/… Maybe this can help you... if you have same question .. otherwise, please elaborate. Commented Jul 21, 2010 at 11:42
  • 2
    You can't.. not directly anyway (due to same-domain policy). You may have to use a proxy. Commented Jul 21, 2010 at 12:45

4 Answers 4

7

Try the following piece of javascript code:

function getReq() {
    var req = false;
    if(window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
    } else if(window.ActiveXObject) {
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            req = false;
        }
    }
    if (! req) {
        alert("Your browser does not support XMLHttpRequest.");
    }
    return req;
}

    var req = getReq();

        try {
        req.open("GET", 'http://www.example.com', false);
        req.send("");
    } catch (e) {
        success = false;
        error_msg = "Error: " + e;
    }

alert(req.status);
Sign up to request clarification or add additional context in comments.

Comments

6

You will have to use XMLHTTPRequest for getting the HTTP status code. This can be done by making a HEAD request to the server for the required url. Create an XMLHTTPRequest object - xhr, and do the following

 xhr.open("HEAD", <url>,true);
 xhr.onreadystatechange=function() {
     alert("HTTP Status Code:"+xhr.status)
 }
 xhr.send(null);

See here for more details.

Comments

2

You can't do this with AJAX directly because of the same origin policy.

You'd have to set up a proxy service on your server then make ajax calls to that with the address you want to check. From your server proxy you can use cURL or whatver tool you like to check the status code and return it to the client.

Comments

0

I assume JavaScript, with JQuery, which simplifies AJAX requests alot, like this.

$.ajax({
  url: 'url',
  type: 'GET',
  complete: function(transport) {
      doing whatever..
  }
});

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.