1

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 the code;

window.onbeforeunload = function () {
         someAjaxObj.saveFavorites(json,{async:false});  // use async:false else callback is returned to an unloaded page creating a dwr javascript error
   }

Now for some reasons, the data does not get saved/reflected after refresh on iPad Safari. I tried changing "onbeforeunload" to "pagehide" for iPad, but still data does not reflect after refresh..

Also just to add the AJAX call is actually a DWR (Direct Web Remoting) call.

Please suggest how I can fix this issue.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

0

Mobile safari doesn't even support onbeforeunload at all.

Alkanshel
  • 4,198
  • 1
  • 35
  • 54
0

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
noob
  • 8,982
  • 4
  • 37
  • 65
  • Thx for your reply...I am not very sure if you are just asking me to display a message to the user on "onbeforeunload"...If that is the case, I also need to actually save the data..coz that is the single place where I have coded to save data...Also I would be unable to make any modifications to that behavior...like adding a Save button or something... – copenndthagen Nov 17 '11 at 09:18
  • Thx again...But I did not quite understand what you are trying to do with the cookie...like at what point of time do we save the data to cookie...Is it during page unload ? If yes, is it not possible that we face the same issue as before (i.e. using pagehide) – copenndthagen Nov 17 '11 at 11:25
  • Also I want to finally persist the data to database using the call to saveFavorites() – copenndthagen Nov 17 '11 at 11:33
  • No you save the changes a soon as something is changed in a cookie (as json string) if someone will go to another link it is like he leaves the page and enter it again, when he enters the page you check if there is the cookie with the changed datas in json string you save the data _so you save the data when the new page is loading_ – noob Nov 17 '11 at 12:21