开发者

delete from database after browser close

I am developing an E-C开发者_如何学编程ommerce application. But the problem is when user adds a product to cart and close the browser before order, the cart takes all the products. All the cart items are saved in a table.

I just want to flush the cart if the user closes the browser without ordering.


You can use Javascript event to catch browser close and sent ajax request to some script that will delete cart data:

UPDATED

<script language="javascript">
function fnUnloadHandler() {
  xmlhttp=null; 
  if (window.XMLHttpRequest) 
     {// code for Firefox, Opera, IE7, etc. 
        xmlhttp=new XMLHttpRequest(); 
     } 
  else if (window.ActiveXObject) 
     {// code for IE6, IE5 
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
     } 

  if (xmlhttp!=null) 
     {  
        xmlhttp.open("GET","http://yourhost/del_cart_actionFile.php",true); 
        xmlhttp.send(null); 
     } 
     else 
     { 
        alert("Your browser does not support XMLHTTP."); 
     } 
}
</script>
<body onbeforeunload="fnUnloadHandler()">
</body>


There's no way of reliably knowing/alerting the server when a user closes his browser. You need to rethink your design: i.e do not persist cart items to the database unless checkout is completed. You can and should keep cart items in the user session, or possibly in cookies client-side (unless your cart sizes are gigantic).

Else key the cart data in the db with the session key. You can then (probably) add some kind of hook to your app's session management to flush the db contents when a session is cleared.


Server side does not actually know when you close the browser. You can ping the server onBeforeClose and tell it to flush the cart, but that would mean that when a user closes a tab - it would flush too.

If your user is logged in - you can keep the session cookies for "browser session" only and that way the user would be logged out when he or she comes back. At this point - whenever a user logs in - flush the cart.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜