Unable to display a custom notification message when attempting to leave a page using the "onbeforeunload" event

I added the following script to prevent leaving the page during processing steps:

<script language="JavaScript">
window.onbeforeunload = confirmExit;

function confirmExit()
{
JQObj.ajax({
    type: "POST",
    url: "<?php echo $this->url(array('controller'=>'question','action'=>'cleaSess'), 'default', true); ?>",
    success: function(data){}
});

return "You are trying to leave this page. If you have made changes in the fields without saving, they will be lost. Are you sure you want to exit?";
}

</script>

However, I keep getting the default alert message instead of the custom one I set.

I also want to trigger the ajax call when the end user clicks on the "Leave page" button, but currently, the ajax call is triggered before clicking the leave button in the script above.

Does anyone have an idea or a solution to only call the ajax when people actually leave the page?

Answer №1

To send an AJAX request when leaving a page, you can utilize the "unload" event:

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "Before you leave, are you sure you want to navigate away from this page? Any unsaved changes will be lost.";
    };

    window.onunload = function() {
        // If the user chooses to leave, execute the AJAX request
        JQObj.ajax({
            type: "POST",
            url: "http://your.url.goes/here",
            success: function() {}
        });
    };
</script>

For a demonstration, check out this quick demo.

Answer №2

Consider implementing a similar solution:

window.onbeforeunload = showConfirmation;

function showConfirmation()
{
    if (confirm("You are about to navigate away from this page. Any unsaved changes will be lost. Are you sure you want to leave?"))
    {
        confirmNavigation();
    }
}

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

Obtain the updated cart total for WooCommerce when the 'updated_cart_totals' jQuery event is triggered

Currently, I have implemented the updated_cart_totals jQuery event to monitor updates to my WooCommerce cart. While this setup successfully triggers when the cart is updated, I am also seeking a way to retrieve the updated total for the cart. Below is the ...

JavaScript Arrays with Four Dimensions

Looking for a solution to generate arrays with any number of dimensions, including 4D arrays. I'm interested in being able to use the function to create an array and then access it like this: arr[3][2][23][12] = "amazing"; ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...

NodeJS continuing to trigger setInterval() even after clearInterval() has been called

I need some help with my NodeJS script that sets and clears an interval. The starting interval works fine, but when I try to clear it, the console shows "stopping interval" yet the interval keeps firing every minute. app.get("/api", async (req, res) => ...

What steps should be taken to restart an AJAX call that has failed previously?

My issue involves an ajax call that must run and if it fails, it should be reinitialized. While I have looked into some posts mentioning a failure function where we can inform the user about the failed ajax call and execute a set of functions. However, I ...

Is there something else I should consider while implementing onBlur?

I am currently working on implementing form validation for a React form that I have developed. The process involves using an onChange event to update the state with the value of each text field, followed by an onBlur validation function which checks the va ...

Begin running the current ajax request while cancelling all prior ones

I'm currently working on creating an auto-complete user interface. There's an input field that triggers an ajax call to fetch relevant data from the server whenever a key is pressed. However, if the user types a word that is 10 characters long, t ...

Developing a unified input element containing numerous fields

After @grateful answered this question, I wanted to elaborate in case it could benefit others... In my project, there's a page called rsetup.php which has some PHP code to access a MySQL database for filling the HTML content of the page. This HTML ge ...

extracting numerical values from a string using javascript

Currently, I am engaged in a project that requires extracting phone numbers from a string. The string is stored in a JavaScript array called dine. { "group": 1, "tel1": "Tél(1): 05.82.77.31.78", "tel2": "Tél(2): 09.55.86.31.45", }, ,... My goal i ...

Is the quantity of ajax requests a significant factor? If so, in what way does it

My website is designed to provide clients with various types of information, including chat features, notifications, and more. To achieve this, I have set up an AJAX call for each chat and notification that occurs every second. This means that there are a ...

Scrolling vertically using window.open functionality

I am trying to open a pop-up window using window.open. I would like the scrollbars to appear only if necessary. Unfortunately, in Safari, the scrollbars do not show up unless I include scrollbars=1 in the code. However, this also causes horizontal scrollb ...

Issue with modifying DataTable's body content via Ajax request

I am working with a DataTable and trying to load data through an ajax call. However, the first line always displays: "No data available in table" https://i.sstatic.net/7gFKx.png Despite this message, the ajax-loaded data is displayed below it. How can I ...

Display the name of the file on the screen

Is there a way to dynamically display the file name in a view instead of hardcoding it? I would appreciate any assistance. Thank you! Here is my code snippet: <li> @if (Model.Picture2 != null) { base2 = Convert.ToBase64String(Model.Pict ...

Utilizing Laravel's pagination feature with the power of AJAX and JSON communication

I currently have four fields that act as filters on my Laravel model. I am utilizing AJAX to fetch response data from the blade template and return it as a JSON response. Below is the function that I am using: public function displayTable() { // These ...

The npm copy script is not functioning properly on the Windows 8.1 operating system

I am working on a sapui5 project and I need to execute the following npm script from my package.json: "scripts": { "flatten": "copy -r \\dist\\resources\\test\\commonjslib\\* dis ...

Could variable scope change during asynchronous jQuery AJAX calls?

I am currently working on a system to track item stock, but I seem to be encountering an issue with the correct updating of statuses. In my JS code, it seems that the values of objects within the $.each loop are what is being utilized for operations like ...

Issue encountered while trying to download Jade through npm (npm install -g jade)

I am having trouble downloading jade via npm on my Mac (Yosemite). After downloading node and updating npm, I tried to install jade but encountered a series of errors that I cannot resolve. Even attempting to use sudo did not help, as it only displayed s ...

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

Unable to pass a variable through ajax to another PHP file

I am currently facing an issue with passing a variable from one PHP file to another using ajax. In my 'index.php' file, there is a button that, when clicked, should pass the button's id to another PHP file named 'show_schedule.php' ...

Implementing a soft transition to intl-tel-input plugin

This tel-input plugin was developed by Jack O'Connor. You can find the plugin here: https://github.com/Bluefieldscom/intl-tel-input I have observed that the flags take approximately one second to download, and I would like to enhance this process wi ...