I have a database with field 'status' which is default 0 when offline and 1 when online. I was wondering if a开发者_开发知识库nybody knows a way to update the database in the event of browser close (set the 1 to a 0). It has been suggested that I use a body unload and point to AJAX but i've no idea how to do it...PLEASE help, thank you...
Here is a simple solution for browser close event. I faced some issue with onunload
and beforeonunload
events. It will be triggered for browser close, tab close, any link click, URL change. So i customized my code like this:
<script type="text/javascript">
jQuery(document).ready(function() {
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
var status = 'abandoned';
$.ajax({
type: "POST",
url: your action URL,
data: "status=" + status,
success: function(res) {
},
});
}
};
});
</script>
Piskvor is dead-on. There is no reliable way to find out when a user is actually leaving your site to, for example, go to bored.com - or if they have two windows open that are both viewing your site, and they decide to close one of them. That's why, for the most part, login sessions expire and websites provide "Logout" buttons - to know for sure.
If you did want to explore this route further, it's as simple as creating a javascript function
function doAjaxThingy(){
var qty = document.getElementById(q).value;
var ajax = getXmlObject();
var url= '/doAjaxThingy.php';
if (ajax.readyState == 4 || ajax.readyState == 0) {
ajax.open("POST", url, true);
ajax.onreadystatechange = function (){
if (ajax.readyState == 4) {
alert(ajax.responseText);
}
};
ajax.send(null);
}
}
function getXmlObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
showError('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.','Please Wait');
}
}
and then let the page know to call that function when it unloads
<body onunload="doAjaxThingy();">
精彩评论