4

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.

4 Answers4

5

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.

Matteo Codogno
  • 1,569
  • 6
  • 21
  • 36
1

Because $.post is an async task browse wont wait until the response came, follow the answer given in this solution - $(window).unload wait for AJAX call to finish before leaving a webpage

Community
  • 1
  • 1
Sandeep Manne
  • 6,030
  • 5
  • 39
  • 55
1

From jQuery API docs

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

It seems like you are using one of those versions of Firefox which handle this event differently. Try the beforeUnload event as mentioned in the Documentation.

Bagira
  • 2,149
  • 4
  • 26
  • 55
-1

If you replace

$(window).unload(function(){        
 $.post("http://localhost/project/quizTime.php",{action:"updateTime",userID:userid,quizID:quizid,newTime:currentTime*1000,rand:Math.random()},function(time)
    {
    });
});

with this:

$(window).unload( function () { alert("Bye now!"); } );

and test, what happen? If appears alert the problem is in $.post...

Matteo Codogno
  • 1,569
  • 6
  • 21
  • 36