How to get response status code from jQuery.ajax?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to get response status code from jQuery.ajax?

How to Get Response Status Code from jQuery.ajax? 🤔

If you're struggling to get the response status code and the 'Location' response header from a jQuery.ajax call, don't worry, you're not alone! Many developers face this issue and find it difficult to debug. But fear not, because in this guide, we will break down the problem, provide easy solutions, and help you understand how to get the desired results. Let's dive in! 💪

The Problem 🔍

In the provided code snippet, the goal is to obtain the HTTP response code and display the 'Location' response header if the code is 301 (Moved Permanently). However, the status code and the response header seem to be missing when inspecting the 'jqxhr' object in Firebug or any other debugging tool.

The Explanation 📝

The issue here is that the 'jqxhr' object doesn't directly expose the status code and response headers as properties. To access this information, we'll need to use the respective methods provided by the object.

Solution: Getting the Status Code 📜

To retrieve the response status code, you can use the status method provided by the jqxhr object. Here's how you can modify your code to achieve that:

function get_resp_status(url) {
  $.ajax({
    url: url,
    complete: function (jqxhr, txt_status) {
      console.log ("Complete: [ " + txt_status + " ] " + jqxhr);
      // Get the response status code
      console.log("Status Code: " + jqxhr.status);
    }
  });
}

By simply adding jqxhr.status, you can access the HTTP response code. Now you can use this information to compare it against the desired code (in this case, 301) and take further action accordingly.

Solution: Getting the 'Location' Response Header 📍

To retrieve the 'Location' response header, you can use the getResponseHeader method provided by the jqxhr object. Here's how you can modify your code to achieve that:

function get_resp_status(url) {
  $.ajax({
    url: url,
    complete: function (jqxhr, txt_status) {
      console.log ("Complete: [ " + txt_status + " ] " + jqxhr);
      // Get the 'Location' response header
      console.log("Location: " + jqxhr.getResponseHeader("Location"));
    }
  });
}

By using jqxhr.getResponseHeader("Location"), you can obtain the 'Location' response header value. Now you can perform any necessary actions based on this information.

Bonus Tip: Handling Errors with Status Codes ❌

To handle error scenarios and specific status codes, you can utilize the error property provided by the jqxhr object. Here's an example of how to handle a specific status code:

function get_resp_status(url) {
  $.ajax({
    url: url,
    complete: function (jqxhr, txt_status) {
      console.log ("Complete: [ " + txt_status + " ] " + jqxhr);
    },
    error: function (jqxhr, txt_status, err_thr) {
      if (jqxhr.status === 404) {
        console.log("Page not found!");
      }
    }
  });
}

In the above example, if the status code is 404 (Not Found), we log a helpful message indicating that the page wasn't found. You can customize this logic based on your specific requirements.

Conclusion and Call-to-Action 🎉

Congratulations! You've learned how to get the response status code and response headers from a jQuery.ajax call. Now you can fetch and utilize this information in your applications with ease. 🚀

If you found this guide helpful, make sure to share it with your fellow developers and spread the knowledge! Don't hesitate to leave a comment or reach out if you have any further questions or suggestions. Happy coding! 😄👩‍💻👨‍💻

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my