Skip to content Skip to sidebar Skip to footer

AJAX Call On Onbeforeunload To Save Data

I have a page where a user performs some activity (Add/Update/Delete) and on unload of the page (actually refresh/navigating away) I make an AJAX call to save the data. Below is th

Solution 1:

the only thing you can do at onbeforeunload event is asking the user if he want's to save before (this is because some pages might open a new window at onbeforeunload and spam with it)!

var saved = false;
window.onbeforeunload = function () {
    if (!saved) return "If you leave the page now your changes won't be saved.";
}

I think the best solution would be to store the changed data in a coockie which will be deleted when the user enters the page and the datas are saved

function getCookie(name) {
var a = document.cookie.split(';');
for(var i = 0; i < a.length; i++) {
    var s = a[i];
    while (s.charAt(0)==' ') s = s.substring(1,c.length);
    if (s.indexOf((name + "=")) == 0) return s.substr((name + "=").length, s.length);
}
return null;
}
if (getCookie("save")) //save datas

Solution 2:

Mobile safari doesn't even support onbeforeunload at all.


Post a Comment for "AJAX Call On Onbeforeunload To Save Data"