-2

I see that Chrome doesn't allow alerts in an unload function

$(window).on('unload', function(){

    alert("ciao");

});

But then how does JSFIDDLE do it?

In dev tools I can see I can tick a box that will stop execution on EventListener Breakpoints --> Load --> Unload

But I cannot see what's really going on. How do they do it?

EDIT: code

    $(window).on('unload', function(){
        //delete files      
        $.ajax({
            type: "post",
            url: "delete_files.php",
            data: {
                test: $("body").data("test_name");
                prod: $("body").data("prod_name");
                prodAd: $("body").data("prodAd_name");
            },
            dataType: "html",
            success: function(returnedData){

                console.log(returnedData);
            }
        });
    });
Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229
  • That is not an alert. You just say `return "your message"' in the unload event. The browser generates a prompt itself. – putvande Aug 08 '13 at 22:32
  • @putvande well, i was just using an alert to debug . this function isn't working at all. the plan was to have it make an ajax call to call a php script. But I can see that that is likewise not working. – 1252748 Aug 08 '13 at 22:34
  • You should be able to call an AJAX request within the `beforeunload` event. The only thing that Chrome doesn't allow is the alert, everything else seems to be fine. What does your code look like? – putvande Aug 08 '13 at 22:35

2 Answers2

1

I grappled with this for awhile about a year ago.

I ended up using this solution:

$(window).on('beforeunload', function() {
    $.get('http://some-page.php');
});

In our case, some-page.php is a JSP that cleans up a user's session.

Further reading about the beforeunload event.

jahroy
  • 22,322
  • 9
  • 59
  • 108
1

Your AJAX call works just fine, after you changed a few things. The data you are sending is an Object. Yours contains ; which will give an error. That is probably why it is not working.

$(window).bind('unload', function(){ 
    //delete files      
    $.ajax({
        type: "post",
        url: "test.php",
        data: {
            test: $("body").data("test_name"),
            prod: $("body").data("prod_name"),
            prodAd: $("body").data("prodAd_name")
        },
        dataType: "html",
        success: function(returnedData){

            console.log(returnedData);
        }
    });
});
putvande
  • 15,068
  • 3
  • 34
  • 50