Search code examples
javascriptjqueryajaxinternet-explorer-8onbeforeunload

javascript: Internet Explorer not sending ajax call before form submit/page unload


Trying to send AJAX POST on form submit. Already have a code working in all browsers except IE.

Working code (except IE)

$('form').one("submit", function(e) {                   
    $.ajax(
     {
       url : url,
       type: "POST",
       data : data,
       async: false,
       complete: function() {  
       return true;
      }
     });  
    });

Tried almost everything I can, like onunload and onbeforeunload, and obviously the general onsubmit (both native Javascript and jQuery methods). But IE won't wait for AJAX calls to finish and loads the form action page.

onbeforeunload would make it wait, but bring a dialogue confirmation box (which I am not willing to show).

Also, async:false doesn't work on IE. I can't use HTTPRequest as the request is cross domain. Again, XDomainRequest is asynchronous, so even that is not useful.

Other ways, like event.preventDefault() won't submit the form after callback.

Note: The form on the page is submitted after successful validation with native submit function. I can't mess that code because it belongs to our client, and we are loading our code asynchronously.

Already checked links: using onbefore unload onbeforeunload with timeout


Solution

  • Had to ditch the general onsubmit/onclick based callback events. Used a workaround. Browsers can save data over the same window/tab using localStorage global object.

    Therefore, on submit button click, saving data in localStorage object

    $('input:image').click(function() {
    //Yes, my client is using image as submit button. No biggie! 
    //form data collection code here
    localStorage.lc = JSON.stringify(data);
    });
    

    On next page (form's action page, my JS is again loaded). Therefore, I can check for the localStorage object, and send the POST data (Using XDomainRequest() due to Cross domain data transfer. Also note the XDomainRequest() needs to be written with all parameters, otherwise request may fail erratically - XDomainRequest Fix.

    window.onload = function() {
     if(localStorage.hasOwnProperty('lc'))
     {
      if(localStorage.lc.length > 0)
      {     
        dataStr = "";
        var lcData = JSON.parse(localStorage.lc);           
        for(var prop in lcData)
        {
          dataStr += "&" + prop + "=" + lcData[prop];
        }
        var url = "https://www.leadscapture.com/lead/track/trackId/" + lcData.trackId;
        var xdr = new XDomainRequest(); 
        xdr.open("POST", url);
        xdr.onload = function() {
          delete localStorage.lc;
        };
        xdr.onprogress = function(){ };
        xdr.ontimeout = function(){ };
        xdr.onerror = function () { };
        setTimeout(function(){
            xdr.send(dataStr.substring(1));
        }, 0);          
      }
    }