tags:

views:

154

answers:

1

Hi All,

I am trying to make a JSONP call to a server on the 'beforeunload' event. This all works great until I start playing with the back button. If I navagate away from the page and then press 'back' next time the beforeunload event gets called it appears to make the JSONP request but the server never receives it.

Note(1): This has been tested on IE and FF (problem appears on both).

Note(2): I have also tested using jQuery.getJSON method and it had the same problem so I assume the makeJSONPCall funciton is correct. (I could be wrong)

Any ideas anyone?

Some code for context:

JSONP CALL:

makeJSONPCall('http://serverurl.mvc/method?args=' + data, 'callbackfunction');   

function makeJSONPCall(url, callbackname)
{                
  if (url.indexOf("?") > -1) url += "&jsonp=" 
  else url += "?jsonp=" 
  url += callbackname + "&";
  url += new Date().getTime();
  var script = document.createElement("script");            
  script.setAttribute("id", "JSONP");
  script.setAttribute("src",url);
  script.setAttribute("type","text/javascript");                
  if (document.head) document.head.appendChild(script);
  else document.body.appendChild(script);    
}

Thanks

A: 

That event is kind of quirky. You might ultimately decide not to use it. First thing, make sure you are making a synchronous post. Next, you will probably need to present a UI to the user in order to keep the browser from changing location too quickly. I used something like the below once and it worked but I ended up doing things a different way.

    window.onbeforeunload = function() {
               // stuff do do before the window is unloaded here.
               if(IsDirty()) {
         //i only want to call ajax if I need to.
                setTimeout(function(){
                    DoAjaxSaveSynchronously (); // this was important
                    ClearDirty();
                        }, 500);
//this return value causes the browser to pop a modal window.
                return "You have unsaved work. Please stay on this page to save your work.";
               }
            }
Chris Schoon
Thanks for the prompt response Chris. Unfortunately being a public utility script I cannot go putting alerts in peoples pages. I actually don't think there is a solution here as there is no way for me to 'wait' in the beforeunload event until I receive the server reply.Thanks anyways
gatapia