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

Button component in React remains visible until interacted with

https://i.stack.imgur.com/gTKzT.png I'm dealing with a sign out component in my app that requires me to click on it specifically to unselect any part of the application. This is implemented using React Material UI. <MenuItem onClick={e => this ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...

What is the best way to create separate positions for items within a single div?

https://i.sstatic.net/FQRY4.jpgAfter looping through various names and accessing them from a single div using {{item}}, I encountered an issue. All the names are within one parent element. This is the code snippet: <div :style="image" cl ...

Utilizing local storage functionality within AngularJS

I've been encountering challenges while trying to integrate local storage using ngStorage in my ongoing AngularJS project. Despite fixing what seems to be the root cause of data type problems and errors during debugging, issues persist. Here is the P ...

I'm having trouble getting my Ajax edit code to function correctly. Can anyone offer some assistance?

I am currently working on a basic registration system that includes two forms: one for registration and another for selecting a city. I have encountered an issue where newly added cities update perfectly, but when trying to use the selected city in the reg ...

Accessing form data using Vue on submit

I'm working on a project that involves creating a form with a single input field and saving the data to a database. The technology I am using is Vue.js. Here is the template I have designed: <form class="form-horizontal" @submit.prevent="submitBi ...

display the designated image as a priority

I am designing a loading screen for my website that includes the loading of multiple images, scripts, and other elements. While the HTML and CSS part is working well, I need to ensure that the "loading..." image is loaded before anything else on the page. ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

Issue with jQuery animation: Background color does not change upon scrolling

Here is my fiddle link: https://jsfiddle.net/jzhang172/owkqmtcc/5/ I am attempting to change the background color of the "content" div when scrolling anywhere within it. The goal is for the background color to change when scrolling and revert back to its ...

Focus is lost on React input after typing the initial character

Whenever I input text, the focus is lost. All my other components are working fine except this one. Any ideas why this might be happening? I attempted to create separate components and render them in my switch statement, but it still doesn't work. O ...

Is there a way to horizontally navigate a pallet using Next and Prev buttons?

As someone new to development, I am looking for a way to scroll my question pallet up and down based on the question number when I click next and previous buttons. In my pallet div, there are over 200 questions which are dynamically generated. However, th ...

Having issues installing Parcel through npm - Encountered an error while parsing package.json information

After creating a package.json file using the command npm init in my project folder, I proceeded to run npm i parcel --save-dev which resulted in an error message: C:\Users\XPRESS\Desktop\starter>npm i parcel --save-dev npm ERR! code ...

Adding and removing content through ajax operations

Currently, I am focused on implementing basic functionality for insert, add, delete, and update operations using ajax. I have made some progress with the functionality but my goal is to incorporate all features in a grid format. To achieve this, I have ...

Transitioning from one bootstrap modal to another in quick succession may lead to unexpected scrolling problems

I'm facing a challenge with two modals where scrolling behavior becomes problematic when transitioning from one to the other. Instead of scrolling within the modal itself, the content behind it is scrolled instead. In order to address this issue, I im ...

Incorrect scope value detected in Angular controller

I recently started learning Angular 1, and I've encountered an issue with my code: var app = angular.module("Football", []); app.factory("competitions", ['$http', function($http) { return $http.get("json/competitions.json") .success(fu ...

Tips for referencing a function declared within a prototype

I have been attempting to enhance a web page by adding functionality using a jquery library that lacks documentation. The problem I am encountering is primarily due to my lack of understanding of the jquery plugin model and/or the inner workings of javascr ...

Error encountered: Failure to locate Yii2 class during an Ajax request

I've created a model class that represents a table in my database: <?php namespace app\models; use yii\db\ActiveRecord; class Pricing extends ActiveRecord { } Next, I attempted to utilize a simple PHP function in a separate fil ...

After a successful login, learn how to implement a bottom tab menu in React Native

I'm diving into the world of react-native and finding myself a bit lost when it comes to routing and navigation. I have 4 screens - Login, Register, Home, and Links. The Register and Login screens are all set up, with the ability to navigate back usin ...

Displaying the scope in HTML from a custom Angular directive: A step-by-step guide

Just getting started with angular js and I have a question. Is there a way to show the values of e.width and e.height in an HTML document? Can I utilize the scope within this context? .directive( "cropping", [function ($scope) { return { rest ...

Using Javascript to dynamically add and remove elements on click

Whenever I click on a link, I am able to generate input, label, and text. However, I want to be able to delete these elements with the next click event on the same link: I've tried updating my code like this: var addAnswer = (function() { var la ...