-3

index.html is:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>

    $( document ).ready(function() {

        var obj = $.get('tmp.html');
        console.log(obj);
        console.log('obj.status:'+obj.status); 


    });

    </script>    
</head>
<body>
    <a href="http://jquery.com/">jQuery</a>

</body>
</html>

Output in console is:

enter image description here

Question is how do I access that status code which is to 200, the way I am doing it shows it's undefined though it's 200

Code on plnkr.co

user4904589
  • 547
  • 2
  • 5
  • 15
  • 3
    The reason it doesn't work in its current state is that you are accessing it before the request finishes. Why do you need to access the status directly if you are using jQuery? The object has built in callbacks for a reason. You should use success, done, always, or fail, or any number of other options rather than directly accessing it. – Rob Foley Nov 05 '15 at 12:54
  • 1
    Some info here: http://stackoverflow.com/a/17547032/1336342 – green Nov 05 '15 at 12:58
  • 1
    Note that little blue `i` - the tooltip for it says something along the lines of the object being re-evalutated when you expand the properties - ie it's (potentially) different from the moment it got logged. – James Thorpe Nov 05 '15 at 12:59
  • 1
    You are accessing it wrong way. use success callback. – Jai Nov 05 '15 at 12:59

3 Answers3

1

Try using this --

$.get("tmp.html", function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
});

or if you want the complete status then try this --

$.get("tmp.html", function(data, status){

}).done(function(data, textStatus, jqXHR) {
    console.log(jqXHR.status  )
  })
Rohan Veer
  • 1,374
  • 14
  • 21
1

Basically the state of the jqXHR object is updated to include status after your call to console.log(). this is nature of asynchronous actions in JavaScript.

$.get() returns a jqXHR object as per this. You need to chain a callback function such as done() to get access to the status code, which will be passed in to your callback function.

Gruff McGruff
  • 280
  • 2
  • 9
1

The correct way to get response code is given below

$.ajax({
//...        
success: function(data, status, response) {
    console.log(response.status);
},
complete: function(response, status) {
    console.log(response.status);
}
Babar Sajjad
  • 195
  • 1
  • 4