Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ondemand javascript call on window unload using jquery

Tags:

jquery

ajax

I have tried for "unload" and "beforeunload" binding in following code, but none of the browser is sending a request:

$(window).bind('unload', function(){
       $.ajax({cache: false,
        dataType: "script",
            url: "test.php"
        });
    });

Any suggestion?

like image 803
Sunil Avatar asked Apr 12 '10 12:04

Sunil


2 Answers

The browser doesn't wait for this code to finish...it's running just fine :) Add an alert('hi') to see it running.

The problem you're seeing is typical of unload issues, the browser navigates away well before a request gets fired off in your case...and it should really, no code you're running should have to complete before I'm allowed to move onto the next page. This is just how unload behaves. You could make the call synchronous to hold the user there, but please don't do this.

The unload event was created on window mainly to clean up anything left around in the DOM you needed to, more-so when garbage collection wasn't as good as it is now (and still isn't in IE)...it wasn't really designed with AJAX or metric tracking in mind.

like image 63
Nick Craver Avatar answered Oct 02 '22 13:10

Nick Craver


Just set the option async to false.

$(window).bind('unload', function(){
   $.ajax({
    cache: false,
    async: false,
    dataType: "script",
        url: "test.php"
    });
});
like image 33
Kru Avatar answered Oct 02 '22 13:10

Kru