开发者

Javascript load/unload to get PHP $_SESSION variables

开发者 https://www.devze.com 2023-04-02 22:38 出处:网络
I\'d like to have a javascript function called on page load and unload which will set and unset a session variable. Currently the javascript (in line with PHP) looks like this (uses jQuery)

I'd like to have a javascript function called on page load and unload which will set and unset a session variable. Currently the javascript (in line with PHP) looks like this (uses jQuery)

window.onbeforeunload = function() {
   $.post('Example.php?y=".$id."&dir=0');
} 

$(document).ready(function() {
   $.post('Example.php?y=".$id."&dir=1');
}); 

These are included in a php script where $id is a variable passed to the page. Example.php is a script called using ajax which simply adds the variable $id to an array stored as a $_SESSION variable, if dir=1, and removes the variable from the array if dir=0.

The issue is that this just SOMETIMES works as 开发者_高级运维expected. When I load the page, the session array is always updated properly. When I unload the page, it sometimes works and sometimes doesn't. My guess is that since these are async functions, the variable is being set by the .ready function call, AFTER a page unload. But the inconsistency persists even if I let the page sit for a while, then unload it. Is there something I'm doing wrong in the unload function?

  • Tried setting ajax:false in the post call

  • Tried using the $(window).unload() jQuery construct, which just didn't work.

  • Using Google Chrome


$.post is asynchronous; this means that when the function returns, the request may still not have been made.

Try making the request synchronously:

$.ajax('Example.php..', {
    async: false,
    type: 'POST'
});

See jQuery.ajax documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消