← Back to jQuery Course | Chapter 10: Advanced AJAX | Lesson 2 of 4

Processing Headers and Status Codes

Response headers contain extra information sent by the server. jQuery lets you read them from the jqXHR object.
Syntax
javascript
$.ajax({
  url: "url",
  statusCode: {
    404: function () { /* not found */ }
  }
});

1. Reading Response Headers

The jqXHR object returned from an AJAX call lets you inspect the raw HTTP response headers the server sent back, such as Content-Type or a custom API header. This is useful when a server communicates extra metadata outside the response body itself, like pagination info or a rate-limit count.

Example: 1. Reading Response Headers

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({url: "data.php", success: function(data, status, jqXHR) {
        $("#output").text(String(jqXHR.getResponseHeader("Content-Type")));
      }});
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

2. Checking Status Codes

HTTP status codes tell you what actually happened to the request, independent of whether jQuery's success or error callback fired. A 200 response usually means success, a 404 means the resource wasn't found, and a 500 means the server itself failed — checking the code lets your code react differently to each case.

Example: 2. Checking Status Codes

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({url: "data.php", success: function(data, status, jqXHR) {
        $("#output").text("Status code: " + jqXHR.status);
      }});
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

3. beforeSend and Request Headers

Use beforeSend to inspect or modify a request right before it's sent, which is the standard place to attach things like an authentication token. The setRequestHeader method on the jqXHR object passed into beforeSend is what actually adds a custom header to the outgoing request.

Example: 3. beforeSend and Request Headers

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "data.php",
        beforeSend: function(jqXHR) {
          jqXHR.setRequestHeader("Authorization", "Bearer token123");
        }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

4. statusCode Option

The statusCode option lets you define separate handler functions for specific HTTP status codes, like 404 or 403, instead of writing one big error handler with if-statements. This keeps status-specific handling clear and makes each case easy to read on its own.

Example: 4. statusCode Option

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "data.php",
        statusCode: {
          404: function() { $("#output").append($("<div>").text("Not found")); },
          403: function() { $("#output").append($("<div>").text("Forbidden")); }
        }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

5. Combining Headers and Status

You can inspect headers and status codes together to build a fuller picture of what happened to a request — for example, logging both the status code and a custom header when debugging why an API call behaved unexpectedly. This combination is especially useful when working against third-party APIs you don't control.

Example: 5. Combining Headers and Status

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({url: "data.php", success: function(data, status, jqXHR) {
        $("#output").text("Status: " + jqXHR.status + "Type: " + jqXHR.getResponseHeader("Content-Type"));
      }});
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading headers with xhr.getResponseHeader("x-token") on a cross-domain request and getting null, because the server must list them in Access-Control-Expose-Headers.
  2. Treating a non-200 status like 404 or 500 as success, when jQuery calls the error callback for those and the code should check jqXHR.status.
  3. Setting request headers after the request is sent, when beforeSend (or the headers option) is where they must be set.
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.