"Enhancing user experience with Ajax and seamless page updates

I'm currently in the process of developing a web application that includes a feature to trigger a backend action that may take up to 5 minutes. This backend process will run independently from the web app's front-end and back-end functionalities.

There is a form on the client side where JavaScript is used to gather, validate, and sanitize the data before sending an Ajax call to the backend to initiate the potentially lengthy process.

My main concern is what happens if a user decides to refresh the page? The backend action will still be activated and carried out, but I am aiming to receive the response once the procedure is completed so it can be displayed in the browser. Is there a way to achieve this?

The Ajax request being made is a simple POST call to my backend:

$.ajax({
    type: 'POST',
    url: '/add-user',
    data: {'data': JSON.stringify(data)},
    //contentType: 'application/json;charset=UTF-8',
    success: function(response){ 
        console.log(response['message'])
    }
    //timeout: 3000 // sets timeout to 3 seconds
});

Answer №1

For further information on handling user prompts before closing a browser, check out this question prompt-user-before-browser-close

To ensure a smooth user experience, consider displaying a loading bar or spinner while waiting for server tasks to complete.

If a user attempts to navigate away from the page, you can implement a confirm prompt.

I highly recommend utilizing a websocket connection and incorporating logic within window.onbeforeunload to notify the backend to cancel any running tasks in case of a premature closure. Failing to do so may leave your backend vulnerable to excessive requests.

Additionally, if the process is independent of the backend, make sure to have mechanisms in place to terminate it upon cancellation of the request context.

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

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Delivering a Captivating JavaScript Pop-Up upon Page Loading

I have a simple pop up window (with no content) that triggers with the 'onclick' event. How can I modify the code below to make the popup appear automatically when the page loads? <head> <title>Popup Display</title> < ...

Guide on making an API call using AJAX from an HTML page in ASP.net

Starting off with ASP.net API, I am attempting to make AJAX calls from my HTML page to retrieve a list of products and search for specific products by their IDs. However, my GET request and the search by ID request do not seem to be functioning properly. ...

Looping through a PHP foreach function, assigning a distinct identifier for the select element using getElementById

My goal is to extract the price value, $option_value['price'], from a dropdown menu as a string rather than using .value, which fetches something different. I am working with select menus generated in a foreach() loop. Each dropdown menu contain ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Handling the display of divs using two select elements

I've been pondering this problem for a while now, and I'm starting to believe that there may not be a solution. Essentially, what I am trying to achieve is the ability to select options from two dropdown menus which will then show or hide specifi ...

How to programmatically update one input value in AngularJS and trigger validation as if it was manually entered by the user?

I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...

Postback asynchronously after clicking on a node in the master page's treeview

My application is being developed using ASP.NET MVC. I have implemented a treeview in the masterpage, with each treenode containing href links. When a treenode is clicked, the corresponding page loads in the content view. I want this process to occur asy ...

Eliminate lower values in select 1 if the value selected in select 2 is higher

I am struggling with a particular piece of code and could really use some assistance. Within my project, I have two select boxes. The first box allows users to select the "from" year, while the second box is for selecting the "to" year. What I'm tryi ...

What is the best way to track the loading progress of an AJAX page in WordPress?

On my WordPress blog, I utilize a plugin known as Advanced Ajax Page Loader. This handy tool loads the next page or post through AJAX and then places it in a specific div on my site. However, I am now interested in incorporating a progress bar to show the ...

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...

invoking a function in javascript from react

Currently, I am grappling with the task of invoking a JavaScript function from within React while adapting a "React" based "Menu" onto some existing jQuery functions. Below you can find my code for the menu: class Menus extends React.Component{ co ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

VueD3tree successfully fetches data, however, it is not being displayed on the screen

Just started delving into Vue and VueD3tree. Attempting to display a tree using the vued3tree library with data pulled from an API. Strangely enough, when trying with static data, the tree displays perfectly fine. However, when fetching data dynamically, a ...

How can you create an animation that plays forward on the first click and then reverses on the second

After coming across numerous similar questions, I realize that most of them refer to the outdated .toggle() function. My main challenge lies in achieving the desired effect where div#p moves right on the first click and then returns to its original positio ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

Using AJAX to dynamically serialize data from a form and POST it in PHP

I have a script on jQuery and HTML5 that dynamically generates a form. Next, I utilize the following code: var OForm = $('#OForm'); // Find disabled inputs, and remove the "disabled" attribute var disabled = OForm.find(':input:disabled&ap ...