How to get Google Chrome to post a form during the beforeunload event


I wanted to submit a form using jquery when the user tries to leave the page. Unfortunately in chrome it doesn't work to just call submit on the form (although it works in other browsers). I think that chrome is just moving on to fast, and doesn't let the submit finish.

Failing code in chrome:

$(window).bind("beforeunload", function (e) {
    $('#form-name').submit();
});

This works in chrome, ie, and firefox.

$(window).bind("beforeunload", function (e) {
    $.ajax({
        type: 'POST',
        url: $('#form-name').attr('action'),
        data: $('#form-name').serialize(),
        async: false
    });
});

Took me way too long to figure this out.

Comments

Popular posts from this blog

The marshmallow cream trainwreck

The start of morels - 2018

In which we blacken someone's name