Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(window).unload wait for AJAX call to finish before leaving a webpage [duplicate]

Basically, once a user leaves a webpage in my application, I need to call a PHP script with AJAX, which will insert a time spent on the webpage to the database and then leave the page.

It is important to wait for the AJAX request to finish because webpages in my application are not accessible to users unless they have spent a certain time on a previous page (let's say two minutes).

Here is my jquery code:

$(document).ready(function() {      var teid = TEID;     var startTime = new Date().getTime();      $(window).unload(function() {         var timeSpentMilliseconds = new Date().getTime() - startTime;         var t = timeSpentMilliseconds / 1000 / 60;          $.ajax({             type: 'POST',             url: '/clientarea/utils/record-time',             data: 'teid=' + teid + '&t=' + t         });     });  }); 

How should I change it so it will wait for the AJAX request to end before leaving the webpage?

EDIT:

Or it might be better (easier) to just let the AJAX request be repeated every minute or so. Is that possible?

like image 343
Richard Knop Avatar asked Jun 29 '10 06:06

Richard Knop


1 Answers

Well, you can set async: false on your AJAX call to make the browser wait for the request to finish before doing anything else, but note that this will 'hang' the browser for the duration of the request.

$.ajax({     type: 'POST',     async: false,     url: '/clientarea/utils/record-time',     data: 'teid=' + teid + '&t=' + t }); 

From the manual:

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

⚠ WARNING: This answer was posted in 2010 and is now outdated - the XHR specification highlights the following statement:

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user’s experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when current global object is a Window object. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an "InvalidAccessError" DOMException when it occurs.

DevTools in Chrome has recently started warning about it, so this change (which has been coming for some years) could be imminent.

like image 156
Tatu Ulmanen Avatar answered Sep 18 '22 01:09

Tatu Ulmanen