Skip to content Skip to sidebar Skip to footer

How To Trigger Onbeforeunload With Back Button In An Ajax Based Application?

I have an ajax based application (ie no page 'reloads` when getting new data). Initially I wanted to find a way to prevent navigation when unsaved data was present on a form. I

Solution 1:

I looked in to triggering window.unload on popstate but didn't have any luck with that.

I ended up changing the logic so that as soon as changes were made, they were saved in the database.

I was using selectize.js for the form input handling and just added some extra calls to it.

In selectize.js (here):

if ($target.hasClass('create')) {
    self.createItem();
} else {
    value = $target.attr('data-value');

became:

if ($target.hasClass('create')) {
    self.createItem();
    $(".saved_message_div").fadeIn(400).delay(2000).fadeOut(400); // new
    updateDatabaseFunction(); //  new
} else {
    value = $target.attr('data-value');
    $(".saved_message_div").fadeIn(400).delay(2000).fadeOut(400); // new
    updateDatabaseFunction(); // new

AND (here):

while (values.length) {
    self.removeItem(values.pop());
}

self.showInput();

became:

while (values.length) {
    self.removeItem(values.pop());
}

$(".saved_message_div").fadeIn(400).delay(2000).fadeOut(400); // newupdateDatabaseFunction(); // new
self.showInput();

And in my own script, the prompt for deleting selectize.js items stayed the same:

onDelete: function(values) {
confirm(values.length > 1 ? 'Are you sure you want to remove these ' + values.length + ' items?' : 'Are you sure you want to remove "' + values[0] + '"?');

Post a Comment for "How To Trigger Onbeforeunload With Back Button In An Ajax Based Application?"