Is there a way to track and capture all live AJAX Requests in order to re-send them seamlessly?

Is it possible to monitor and intercept all dynamic AJAX requests and then resend them afterwards? How can this be achieved?

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(value) {

    this.addEventListener("error", function(){
        /* 
           I need to resend the request using XMLHttpRequest at this point
           The resend requests are dynamically generated
           For example, "new XMLHttpRequest(this).send()"
           Using AJAX is also acceptable
        */
    }, false);
    this.realSend(value);
};

Answer №1

Here is a helpful snippet for handling AJAX calls effectively. Execute this code as soon as possible to ensure it works for subsequent AJAX requests.

It's important to address failed requests promptly as they can compound if left unresolved. This script allows for automatic retries, incrementing with each failed attempt.

Keep in mind that you may need to make adjustments to retrieve responses from nested requests once they succeed.

// Override 'send' with 'open' to intercept requests early.
XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;

// Track retry attempts per request to prevent infinite loops.
XMLHttpRequest.prototype._maxRetry = 5;
XMLHttpRequest.prototype._currentRetry = 0;

XMLHttpRequest.prototype.open = function open(...args) {

    if (!this._currentRetry) {
        console.log('REQUEST CAPTURED.');
    }

    this.addEventListener('error', () => {
        // Abort the current request.
        this.abort();

        // Check the number of retries.
        if (this._currentRetry >= this._maxRetry) {
          console.log('MAX RETRY REACHED.');
          return;
        }

        console.log(`RETRYING ${this._currentRetry} of ${this._maxRetry}.`);

        // Create a new request instance.
        const req = new XMLHttpRequest();
        
        // Copy updated retry numbers to the new instance.
        req._maxRetry = this._maxRetry;
        req._currentRetry = this._currentRetry + 1;
        req.responseType = this.responseType;
        
        // Send the new request using previous arguments.
        req.open(...args);
        req.send();
    });

    // Call the original 'open' method.
    this._open(...args);
};

const test = new XMLHttpRequest();

test.open('GET',  'https://asfashdg');
test.send();

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

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Toggle display of fields based on radio button selection in ASP.NET

I am new to C# asp.net and I am working on creating an online registration form. I am facing a challenge with the following issue. Could someone assist me, please? There are 5 fields in this problem: 1) Category: radio button with options for St ...

Thumbnail image preview fails to display after preloading an image in dropzonejs

Currently, I have a form where users can input their name and upload an image (logo). The client side language being used is AngularJS with dropzonejs as the image upload library. When the user clicks on the 'Edit' button, I want them to see a pr ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

Offspring of div should have equal height without the top and bottom padding

Looking to ensure that the height of child divs matches the height of the parent divs. Currently, the divs expand as the page is resized. This is for search results, so there are multiple identical code blocks. function matchHeight() { $result = $(&a ...

Removing an item from a JSON array based on its value using jQuery

This is a section of my JSON array: var videos = $j.parseJSON(' [ { "privacy":"public", "id":"1169341693" }, { "privacy":"private", "id":"803641223" }, { "privacy":"public", "id":"1300612600" }, ...... When I use co ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

Key-based user retrieval is unavailable in Express, "findAll" can only be done through email

I've created a straightforward Express/Pug application designed for searching users in a database by "email" or by "key". In this setup, each user is assigned a unique string as their key. The structure of my user model and index model files can be se ...

execute a series of asynchronous functions one after another

async function cancelUserSubscriptionHandler() { const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", { method: "PATCH", body: JSON.stringify(), headers: { "Content-Type": "appli ...

Ways to retrieve parameters on a PHP page using AJAX and the $.post method

I'm brand new to web development and PHP, currently working on building a website. I am looking to implement a chat session feature, however, I am encountering an issue where the parameters are not being passed to another page when the user clicks the ...

Is it better to create routers on the client side using React, or should one opt to use Express router on the server

As I embark on my journey to learn React, I have been delving into books for guidance. However, one question that lingers in my mind is how to elevate my application to a more professional level. I recently came across react-router-dom and explored the i ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

What is the best way to implement a scope function that will generate and return JSON data in Angular?

I have a function that looks like this: $scope.GetDays = function() { $http.post("core/ajax/LoadDays.php").success(function(data){ return data[0].days; }); }; Within LoadDays.php, the json is as follows: [{"days":"1"}] ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Error loading code. Works when manually pasted, but not when executed with JavaScript

After some trial and error, I found that this code works perfectly if I manually copy the content from the class isotope in 1.php to the class grid on this page. However, when I try to use JS to do the same thing, it mysteriously stops working. Any sugge ...

Altering Collada texture information during the loading process of the .jpg file

Is there a way to modify the texture image data, such as changing the .jpg header text, when loading the .jpg texture in three.js? I am curious if the texture data is accessible somewhere within the code, possibly as a string. How could I go about this? ...

React Hooks: implementing a toggle feature for elements on a map display

In the following loop, two components are being loaded. The desired behavior is to only display <Image /> by default. However, when the element is clicked, it should transform into <YouTube /> (only the one that is clicked, not all). This fun ...

The visibility of JavaScript script to Tomcat is obscured

Working on a web project using servlets and JSP in IntelliJ. One of the JSP files manages graphics and user forms with graphics.js handling graphics and form validation done by validator.js. The issue I'm facing is that while Tomcat can locate graphi ...

Gather data from a span class (Web Development)

<span class="score" title="286 up, 34 down">252</span> How can I modify the code to display both "252" and "286 up, 34 down"? I am not the owner of the website. Would using a CSS Mod like "Stylish" be able to achieve this, or would I need to ...

Step-by-step guide on Setting up the bronto.sca.cart object using Bronto JSON

I have implemented the Bronto Tag Manager to track cart details successfully. After including the Bronto Commerce JavaScript snippet on my page, I am now able to create the bronto.sca object. While bronto.sca.config() and bronto.sca.id are returning valu ...