The browser unexpectedly cancelled the ajax call triggered by the beforeUnload event

Seeking advice on a web application that needs to save user input data through an ajax call when they leave the site.

Currently using "Fetch" in a beforeunload event listener, but encountering issues with browsers cancelling the ajax call (specifically the preflight OPTIONS call being cancelled in Chrome's network panel).

Jquery's synchronous ajax call option is deprecated, and prompting users with a browser-based confirmation message via beforeUnload event is not ideal for business requirements.

Is there a solution to ensure the Ajax call goes through successfully?

Sample code snippet provided below:

window.addEventListener('beforeunload', beforeUnloadHandler);

beforeUnloadHandler(event) {
    fetch(url, {
      method: 'PUT',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        Authorization: api.AUTHORIZATION_HEADER
      },
      body: JSON.stringify(data)
    })
  }

Answer №1

Dealing with a comparable problem, I resolved it by configuring the ajax call as not asynchronous, and it did the trick.

Give this snippet a shot in your ajax call:

$.ajaxSetup({ cache: false })
$.ajaxSetup({ async: false })

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

Tips for implementing ajax and codeigniter to load additional comments on a web page

Is it possible to customize Codeigniter's default pagination to achieve a "viewMore" link style when loading more records using AJAX? The challenge lies in creating a div that automatically expands to handle large numbers of records, such as 10,000 a ...

Utilize AJAX to connect to a remote domain from an extension

I am currently working on creating a Chrome extension that will utilize AJAX to fetch data from a specific webpage and then generate notifications based on the content of that page. The webpage I am targeting is a ticketing system, and my goal is to deter ...

What is the best way to access and verify data from an array that has been passed through props

I am working with a component that takes an array as a prop <Component runners={['1','2']}/> Inside this functional component, my goal is to generate an element for each value in the array. Here's my logic: const { runners ...

Ajax request unable to load Image Slider

I'm currently implementing an Image Slider from this source For the site structure, I've set up an index.html file to display all the pages, allowing navigation by changing the content within <div id="isi">. Here's a snippet of the in ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

Is it possible to create a cookie that is only present when a specific webpage is being

The statement says it all. I am in need of a way to transfer some specific metadata to the client using a cookie that is related to the current page being viewed. I prefer not embedding it within the HTML code, as the metadata is only available after the e ...

The Position of the WebGL Globe Within the Environment

I've been experimenting with the WebGL Globe, and I have successfully made it rotate. However, I'm struggling to figure out how to adjust its position so that it's not centered in the scene. After making changes to the code found at https:/ ...

Incorrect .offset().top calculation detected

Within a webpage, I have multiple sections. Positioned between the first and second section is a navbar menu. As the user scrolls down and the navbar reaches the top of the page, a function is triggered to fix it in place at the top. While this functionali ...

The input box fails to show larger values on the user's page

Show me the biggest number that the user enters in an input box and then display it back to them. I need some improvements to my code, ideally making it possible with just one input box instead of two. <!DOCTYPE html> <html la ...

Incorporating imports disrupts the script configuration in Nuxtjs 3

Issues arise when utilizing the import statement within the context of <script setup>, causing subsequent code to malfunction. After installing the @heroicons package and importing it as a component in the <template>, all code below the import ...

Encountering 'Error 405 - Method not Supported' while making an Ajax POST request in ASP.NET Web API

I am currently in the process of developing a straightforward Web API service that captures input data from an HTML form, converts it into JSON format, and forwards it to a Web API. My coding platform is ASP.NET Web API on Visual Studio 2017. To further el ...

When utilizing jQuery $.post to send hidden input values, there may be the potential for empty database columns and encountering an

I have encountered an issue where I can view the values passed in the console, but nothing gets stored in the database and I keep getting undefined errors as output. Rather than attributing this error to my JavaScript code, I believe the problem lies in ho ...

Having trouble creating a PDF from HTML

Having trouble with generating PDFs using various libraries as I keep encountering the following error: Fatal Error: spawn UNKNOWN The code snippet looks like this: mammoth.convertToHtml({ path: './backend/common/template.docx' } ...

If I use npm install to update my packages, could that cause any conflicts with the code on the remote server?

As I navigate through the numerous issues, I stumbled upon the command npm ci that is supposed to not change the package-lock.json file. However, when I attempt to run npm ci, it fails: ERR! cipm can only install packages when your package.json and package ...

What causes the scrollbar to move while I am dragging the div downward on the page?

$('#aaa').draggable(); * { margin: 0; padding: 0; } #aaa { width: 800px; height: 800px; position: absolute; background: red; } .wrap { height: 2000px; position: relative; ; } <div class="wrap"> < ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

A SyntaxError was caught due to an unexpected token '<' in the constants.js file when using react and vite

I'm trying to display a button in the sidebar with a name and an icon. I've been iterating through the list of categories, which are imported from the 'constants.js' file located in the utils folder. However, instead of getting the desi ...

PHP - Dynamically append data to an array stored in a cookie when a button is clicked

I am looking to update the values of an existing array variable within a cookie. Currently, I am setting my cookie using Ajax: Ajax: function setcookie(productid){ $.ajax({ type: 'POST', url: "setcookies.php", ...

`When is it appropriate to utilize dispatch within an action creator function?`

I have created two functions in my ActionCreator.js file. First: export const fetchAudioForVerification = ()=>{ return fetch(baseUrl+'audio',{ // Perform Get Request } .then(response=>response.json());} Second: export const handleAudio ...