Is it possible to determine if an AJAX request is still ongoing when a user returns to a webpage using jQuery or JavaScript?

Users on a specific page must click a 'generate' button to create details for a record. When the button is clicked, an ajax request is triggered to generate the record, which may take some time.

$("#generate_record_button").on("click", function() {
    $(this).addClass('disabled');
    // Show loading messages and spinner
    $.ajax({
      url: "<generate-record-url/>",
      method: 'get',
      data: {id: <recordID>},
      cache: false
    }).success(function (data) {
       // Handle success scenario
       // Display success messages
       // Remove spinner
    }).fail(function (data) {
       // Handle failure scenario
       // Display error messages
       // Remove spinner
       $(this).removeClass('disabled');
    });
});

In the code, the button becomes disabled after being pressed to prevent multiple ajax requests when continuously clicked. The intention is for users to press the button once and allow the ajax to manage the request.

Is it possible to check if the ajax request is still running when a user leaves the page (e.g., refreshes or navigates away)? If a user returns to the page while the ajax is processing the record, I want the button to remain disabled with loading messages displayed. Can this be achieved?

Answer №1

It is important for your users to remain on the page while an ajax request is in progress to avoid cancellation.

Would you consider implementing the following code snippet?

$(window).on('beforeunload', function(){
  if ($("#generate_record_button").hasClass("disabled"))
    return 'Are you sure you want to leave?';
})

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

The Select2 plugin and managing the removal of selected data

I am currently utilizing the popular jQuery-based Select2 library version 3.3 as a replacement for select boxes. Specifically, I am experimenting with an example involving an ajax call to retrieve data from RottenTomatoes (refer to the Loading Remote Data ...

Struggling to get the hang of CSS animation?

Here is a code snippet that I am using: //Code for animating skills on view document.addEventListener("DOMContentLoaded", function(event) { function callback(observations, observer) { observations.forEach(observation => { if (observati ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Display the variance in values present in an array using Node.js

I am facing a challenge and need help with printing arrays that contain both same and different values. I want to compare two arrays and print the values that are present in both arrays in one array, while also creating another array for the differing val ...

Exploring ways to connect my React application with a node backend on the local network?

On my MacBook, I developed a react app that I access at http://localhost:3000. In addition, I have a nodejs express mysql server running on http://localhost:5000. The issue arises when I try to open the IP address with port 3000 in the browser of my Window ...

Utilizing GraphicsMagick with Node.js to Extract Page Frames from Multi-Page TIF Files

I am currently working with a JavaScript script that can successfully convert a single page TIF file to JPEG. However, I am facing difficulties in determining whether "GraphicsMagick For Node" (https://github.com/aheckmann/gm) has the capability to extra ...

Why won't my navigation bar stay in place when I scroll down on the screen?

I'm trying to create a sticky navigation bar that becomes fixed when the user scrolls down to 200 pixels, but it's not working properly. I want it to behave like in this example: import React,{useState,useEffect} from 'react' functio ...

When a function is called, retrieve a specific number of elements from an array using the slice method in

If I have an array of 15 objects, but I am only displaying 5 on the browser using this code: const displayedArray = array.slice(0,4) I also have a function that will load another 5 objects each time a user scrolls down. displayedArray.concat(array.slice ...

Set a dynamic pixel height for a div to enhance the smoothness of slideToggle animation

I'm struggling with creating a slideToggle menu bar for my responsive layout that uses percent width instead of pixels. The issue I'm facing is that the slideToggle function appears to be jumpy due to this setup. Are there any better alternatives ...

display and conceal elements and refresh action

Can anyone help me with a function to hide and show a div? function toggledDivVisibility(divName) { if (divName.is(':hidden')) { var hiddenDiv = document.getElementById("filter"); hiddenDiv.style.display = 'block&a ...

The display of 'App' seems to be experiencing issues within the render method

Can someone help me with this issue? I am encountering the following error: Uncaught Error: Invariant Violation: Element type is invalid - expected a string for built-in components or a class/function for composite components, but received an object. Bel ...

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

How can I retrieve the reference number of an item by clicking a button within a list item in an unordered

Presented here is a collection of data points and a button nested within an ul <ul> <li class="mix" category-1="" data-value="600.35" style="display:block;"> <figure> <figcaption> <h3> ...

I am experiencing some unwanted movement of divs when I hide one element and show another. Is there a way to prevent this from happening

My webpage features a dynamic div that transforms into another div upon clicking a button. Although both divs share similar properties, clicking the button causes some elements to shift unexpectedly. Strangely enough, when the height of the replacing div i ...

Issue with OnChange Not Triggering

Why isn't the onchange property firing when typing in my textbox? Check out the code below: VB.NET Dim textBoxUrlYoutube As New TextBox divUrlTextBoxContainer.Controls.Add(textBoxUrlYoutube) textBoxUrlYoutube.CssClass = "textboxyo ...

The npm error message states: "Unable to locate the 'readable-stream' module."

Recently, I installed node js on my Windows 10 machine with version v4.4.2. However, whenever I attempt to run npm install or check npm version, it throws the following error message. Any assistance on this matter would be highly appreciated. Error: Canno ...

jQuery forsake any unresolved AJAX requests

Is there a simple method to cancel all active jQuery AJAX requests? In my application, handling multiple simultaneous requests can create issues due to race conditions. I have implemented temporary solutions like using flags to check request completion s ...

Unforeseen behavior in event binding causing knockout knockout

I implemented an event binding for the scroll event on a DIV. To add debounce functionality to the handler, I created a function on my model that generates the debounced handler. Then, in my view, I bind this factory function. I assumed that my factory fu ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

The Material UI Drawer stays closed despite the state being set to true

Currently, I am in the process of developing a WebApp utilizing React and Material UI. Despite following numerous tutorials on implementing the Drawer component and poring over the documentation, I am still struggling to grasp its functionality. Even thou ...