An empty response was received after making an Ajax request

Attempting to create an Ajax request and parse the response header to extract the "Location" attribute. Here is the code in question :

let request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if(request.readyState == 4 && request.status == 301) {
        alert('test');
        let header = request.getResponseHeader('Location');
        console.log(header);
    }
}
request.open('GET', hrefAttr, true);
request.send(null);

The issue arises when I send the request and receive the response (indicating a red "GET" in Firebug), yet no "test" alert or any output in the firebug console.

MODIFIED CODE:

let request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
    if(request.readyState <= 3 && request.status == 301) {
        alert('test');
        let header = request.getResponseHeader('Location');
        console.log(header);
    }
    else if (request.readyState == 0 && request.status == 301) {
        alert('state0');
    }
}
request.open('GET', hrefAttr, true);
request.send();

Sequence of states logged with console.log(request.readyState) : 1, 1, 2, 4.

In the Firebug console tab, the Http Request+Response display correctly but appear in red (if that holds significance).

Uncertain as to why it's not functioning... Edit: Utilizing Firefox.

Thank you for your assistance!

Answer №1

Regrettably, the XHR will adhere to the 301 redirect and display the content of the redirected page. The behavior can be found documented on the W3C website.

If the XMLHttpRequest origin matches the origin of the request URL, it will transparently follow the redirect while adhering to same-origin request event rules.

In essence, your request is seamlessly following the 301 redirect. The browser automatically redirects, preventing you from achieving your intended action. If you have control over the web server, this can potentially be modified (although not recommended).

I hope this explanation clarifies things for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Jquery's .GET method to retrieve and handle JSON data

In the jQuery snippet below, I am trying to fetch product data from . However, I am facing difficulty in iterating through the loop to access all 30 products along with their details. $.get("https://dummyjson.com/products/1") .done(function ...

Exploring the possibilities of using jQuery to access global variables in node.js

My issue has 3 main components. I need to declare a server-side (node.js) variable to store data for the duration of the server run, specifically just a number. I must send a number from the client (jQuery) to the server in order to update the server v ...

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

Ensure that PHP form validations are checked when submitting the form using jQuery

I have created a form in HTML with basic verification. Here is the code: <form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form"> <input class="form- ...

Unable to assign Object for Attribute in Execute JavaScript with Robot Framework

Is it possible to set an Object as the value attribute using Execute Javascript in the robot framework? It seems to work with C#, but I am encountering some issues. InputTeasersForPageType [Arguments] ${id} ${result}= Set Json Value {"P ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

What is the best way to retrieve a response from a PHP file as an array through Ajax?

Seeking assistance in retrieving a complete address by entering the postal code in an HTML form textbox and clicking a button. The setup involves two files - one containing the ajax function and the other housing the PHP code. Uncertainty looms over whethe ...

Complete a checkbox entry form and showcase it within a "division" on the current page

Hello everyone, I need some help. I have a form that I want to send to a specific div on the same page. This is what I am aiming for. I have a floating div named "basket" in the top right corner of my page where I want the form data to be displayed after s ...

Navigating an indefinite amount of state variables in React.js: A comprehensive guide

Receiving data from the server with an unknown number of items in the API leads me to utilize the map method in HTML for rendering. Below is the return section: if (loading) { return ( <div> <div> <Header /> ...

jQuery cannot interpret JSON response when using the $.post method

Essentially, I have a form that, when submitted, sends data to a server-side script to execute a function and returns data in JSON format for me to display on the page. Using jQuery, the data is sent to "createUser.php" using the $.post method $("#cre ...

Javascript - Single line conditional statement

As I continue to improve my JavaScript skills, I'm looking for guidance on optimizing the following if statement. Is there a way to shorten it, possibly even condense it into one line? How can I achieve that? onSelect: function (sortOption) { th ...

Service in Angular JS dispatching coordinates to controller

I am in need of retrieving a path consisting of latitude and longitudes for displaying on a map within my app. To handle all the API calls, I have set up a basic controller. function mainController($scope, $http){ $http.get('/api/lastrun') ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

Adjust the CSS content using the data-content attribute to include line breaks

My current coding setup includes: <div id="mydiv" data-content="Loading..."></div> This is how I style it with CSS: #mydiv:after{ content: attr(data-content); height: 100%; opacity: 1; position: absolute; text-align: center; ...

Is there a way for me to determine which class has been selected using jQuery and JavaScript?

I created a list containing various links: <li class="link-1"><a href="#">One</a></li> <li class="link-2"><a href="#">Two</a></li> <li class="link-3"><a href="#">Three</a></li> .. Wh ...

Tips for deleting default text from MUI Autocomplete and TextField on click

I am currently using Material-UI (MUI) Autocomplete feature with a TextField element, and I have a specific behavior that I would like to achieve. Currently, when I click on the search bar, the placeholder text moves to the top of the TextField. However, m ...

What are the best ways to personalize the Ant Design table and pagination component?

Is there a way to customize and design table and pagination components? Specifically, I am looking to set the header color of the table as green. How can this be achieved? Similarly, for the pagination component, I want to have a background color on page n ...

difficulties encountered while inserting a script tag linking to a local file within an android webview

I have created an Android app with a simple WebView that loads a local HTML file from the assets folder in the project directory. The HTML file includes a tag that makes an AJAX call to an external service and expects a response in the form of a String re ...

Issue with JavaScript Onclick Event Handler

Rephrasing Full JavaScript Code. Javascript <div id="PopUp1" style="display: none; color: #FFFFFF;"></div> <div id="Mask"></div> <script type="text/javascript"> var Content = '<p>Content!!!!!</p><input ty ...

Issue with npm package mail-listener2: Attachments not being saved for emails received from Outlook 2016

I am attempting to retrieve attachments from Outlook, saving them in a specific folder as outlined in the configuration: { username: "username@here", password: "password", host: "hostName", port: 993, connTimeou ...