Question

On a certain page under certain conditions I need to run an update statement in SQL on page unload. It needs to be complete before the user reaches the next page. I'm using JQuery 1.8.3. Here's where I started:

$(window).unload(function() {
    $.ajax({
            type: "POST",
            cache: false,
            url: "myScript.php",
            data: ({ /* my data */ }),
            success: function(result) { /* do nothing */ },
            error: function(data) { location.reload(); }
    });
});

Using this method the update statement didn't run. Through reading up on it I tried "async: false" which didn't seem to fix my issue at first, until I checked my table and saw that the value was updating (only after adding "async: false"). According to further reading, "async: false" has been deprecated in JQuery 1.8, but is still working to execute the update statement. The problem is the update statement doesn't finish executing until the next page's select statements are already completed, so the data is out of date unless the user refreshes the page. Is this due to partial support for "async: false" in 1.8, slow execution of write to db vs fast execution of read from db, some other latency issue, or ??? Is the next HTTP request possibly going through even though the unload event is keeping the user on the page?

Was it helpful?

Solution

solved:

$(window).on('beforeunload', function() {
    $.ajax({
            type: "POST",
            async: false,
            cache: false,
            url: "myScript.php",
            data: ({ /* my data */ }),
            success: function(result) { /* do nothing */ },
            error: function(data) { location.reload(); }
    });
});

$(window).onbeforeunload(...); didn't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top