jQuery post on window.unload(window or browser close)

jquery

Solution

You must use ajax method with async option set false, like this:

$.ajax({
    type: 'POST',
    async: false,
    url: 'YOUR_URL',
    data: 'YOUR_DATA'
});

In this way browser wait for the request to finish before doing anything else.

Problem

I need to send a post request when the user leaves the page in whichever way. So far this is what i have, but it's not working: ``` $(window).unload(function(){ $.post("http://localhost/project/quizTime.php",{action:"updateTime",userID:userid,quizID:quizid,newTime:currentTime*1000,rand:Math.random()},function(time) { }); }); ``` the PHP code was tested by replacing window.unload with a click function. That works perfectly and updates everything as needed, which means the problem is with that $(window).unload trigger.

Original source

Related problems