Monitor the completion status of all Ajax requests using only JavaScript

I am aware of the ajaxStop method in jQuery.

$(document).ajaxStop(function() { //Do something });

If jQuery is not available, is there a way to achieve this with pure JavaScript instead?

If so, could you please provide an example?

Thanks

Answer ā„–1

Alright, I'll tackle this (even though it seems like you're taking the lazy route by not even attempting):

Referencing the jQuery documentation:

After each Ajax request is completed, jQuery checks for any remaining outstanding requests. If none are left, jQuery triggers the ajaxStop event. Any functions registered using the .ajaxStop() method will then be executed.

So what do you need to do? You'll require a central API (or a module) that handles AJAX requests. Within this module, you must keep track of ongoing requests and remove them once they are finished.
If there are no pending requests, you can then check the ajaxStop queue for any registered callbacks and run them.

A basic structure in pseudo-code would resemble the following:

var myAjax = (function()
{//create closure scope to track ajax requests
    var activeRequests = [],
        stopQueue = [],
        ajaxModule = {},//the module itself
        createXhr = function(){};//function to create XHR requests
    ajaxModule.ajax = function(params, callback)
    {
        var xhr = createXhr(params),
            key = activeRequests.length;
        activeRequests.push(xhr);//add to active array
        xhr.onreadystatechange = function()
        {//assign internal handler
            if (this.readyState === 4 && this.status === 200)
            {
                //invoke passed callback only if request is done
                callback.call(this, []);//pass params as you please
                activeRequests.filter(function(e)
                {
                     return e !== this;
                }, this);//define this callback in closure, of course
                if (activeRequests.length === 0)
                {//no more active requests
                    stopQueue.map(function(callback)
                    {
                        callback();//invoke callbacks
                    });
                }
            }
        };
    };
    return ajaxModule;//expose module
}());

Naturally, you will still need to write the functions managing the stopQueue callbacks and develop a trustworthy AJAX module on your own. However, this represents a straightforward setup that could be useful.

Answer ā„–2

Using the abort(); method in JavaScript can be helpful when you need to cancel a request. For more information, you can visit this link:

var httpRequest = null;
function sendRequest() {
    if (!httpRequest) {
        httpRequest = createHTTPRequestObject();
    }
    if (httpRequest) {          

        var url = "file.php";

        httpRequest.open("GET", url, true);  
        httpRequest.onreadystatechange = onStateChange;
        httpRequest.send(null);
    }
}

function abortRequest(){
  if(httpRequest)
      httpRequest.abort();
}

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

A guide on changing a plus sign into a minus sign with CSS transition

Is there a way to create a toggle button that changes from a plus sign to a minus sign using only CSS, without the need for pseudo-elements? The desired effect is to have the vertical line in the "+" sign shrink into the horizontal line. While I know it& ...

What causes the entire page to refresh when using ValidatorCallOut in the Ajax Control Toolkit?

After downloading the Ajax Control Toolkit, I am trying to integrate its components into my project. I have utilized the ValidatorCallOut Component as an extender for a Textbox, so that when the user switches focus to another Textbox, the ValidatorCallOu ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

Should you include the dollar sign in a Vue HTML variable or not?

Iā€™m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Weekly downloads for NPM show no activity

https://i.stack.imgur.com/4Uhk4.png https://i.stack.imgur.com/0vikS.png Why are all the weekly downloads showing zero for npm packages? I'm new here and confused about why this is happening, any insights? If you could please help me open this issue ...

Issue when attempting to update user profile picture using Mongoose schema and Cloudinary

updateProfile: async function(req, res) { try { const update = req.body; const id = req.params.id; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.&a ...

Real-time validation using Ajax and Rails 3

I am currently working with Ruby on Rails 3, UJS, and jQuery. My goal is to create an AJAX form that includes live validation functionality. Even though the form remains a normal form, the attribute remote-data=>true is added for AJAX processing. The form ...

The Google Maps API has been successfully initialized, however, it is experiencing difficulties being displayed on the webpage

I have been successfully using a custom Google API on various web pages. However, I encountered an issue where the map API loads successfully but is not displaying on a specific web page. Below are the relevant code snippets: <html> <head> &l ...

A tool that enhances the visibility and readability of web languages such as HTML, PHP, and CSS

Looking to organize my own code examples, I need a way to display my code with syntax highlighting. Similar to how Symfony framework showcases it on their website: http://prntscr.com/bqrmzk. I'm wondering if there is a JavaScript framework that can a ...

Attempting to activate template rendering with Meteor session

I'm currently facing an issue with Meteor sessions and how my code is triggering the rendering of a template. At the moment, I have a session that sets its ._id to whatever is clicked. Template.sidebar.events({ /* on click of current sidecat class ch ...

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

angular 2 checkbox for selecting multiple items at once

Issue I have been searching for solutions to my problem with no luck. I have a table containing multiple rows, each row having a checkbox. I am trying to implement a "select all" and "deselect all" functionality for these checkboxes. Below is an example o ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

Modifying the height of the bar in Google Charts Timeline using react-google-charts

I am currently working on a Google Chart timeline using react-google-charts. <Chart chartType="Timeline" data={data} width="100%" options={{ allowHtml: true bar: { groupWidth: 10 }, }} ...

Managing data binding for checkboxes within a constantly changing set of options

I'm currently working on designing an angular directive for selecting items from a categorized list. Each item in the list should be selectable using a checkbox. The input data that will be provided to the directive looks something like this: [ { ...

Understanding Pass by Reference within Objects through Extend in Javascript with underscore.js Library

When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example: var obj = {hello: [2]}; var obj2 = {hola: [4]}; _.extend(obj, obj2) obj2.hola = 5; conso ...

What is the best location to manage errors within a sequelize ORM query?

I am working with the Sequelize ORM within a Node/Express environment. My database has two tables: one for Users and another for Items. The Item table includes a foreign key that is linked to the UserId in the User table. Whenever I attempt to create an ...

Tips for handling imports and dependencies in a React component that is shared through npm

Hello everyone, I'm diving into the world of sharing React components and have encountered an interesting challenge that I hope you can help me with. Currently, I have a button component in my app that is responsible for changing the language. My app ...

Running a server-side function on the client-side in Node.js

I am currently working with the following code snippet on the server: var game = io.listen(app); game.sockets.on('connection', function(socket){ storePlayers(socket.id); //Only the player who connects receives this message socket.em ...