0

I have functionality in which I need to make a ajax call to update the database value before closing the browser using 'X' button of browser. I have used below code in the header of associated file:

$(document).ready(function() {
     window.onbeforeunload = function(){
        $.ajax('<?php echo base_url();?>index.php/ajax/myfunction?a=4');
     }
});

On closing the browser the function works but ajax call is not executed..

What's the solution?

OM The Eternity
  • 15,694
  • 44
  • 120
  • 182
  • 1
    You'll have to do synchronous call instead of async. Unfortunately, in the lastest version of jQuery `async` is deprecated – asprin Mar 07 '13 at 12:23
  • @asprin - can you provide a reference please, I did not see that in the 1.9 or 1.9.1 release notes – Mark Schultheiss Mar 07 '13 at 12:52
  • 1
    There you go http://api.jquery.com/jQuery.ajax/ Head to the `async (default: true)` section. It's mentioned in bold letters – asprin Mar 07 '13 at 16:29
  • but only with $.Deferred? to quote: "As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated;" - seems like a bit of a confusing statement to me. – Mark Schultheiss Mar 07 '13 at 17:12

1 Answers1

2

Maybe not the prettiest code but spawning the ajax call in a timeout thread work well cross browser in my experience

$(window).bind("beforeunload", function (e) {
    setTimeout(function(){
        $.ajax({
            type: 'GET',
            async: false,
            url: "[YOUR API CALL]"
        });
    }, 0);
});

Note the last time i used this was on a project using Jquery 1.7

Matthew.Lothian
  • 2,072
  • 17
  • 23