Behind the screen
Behind the screen

Reputation: 71

delete from database after browser close

I am developing an E-Commerce 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.

Upvotes: 2

Views: 3589

Answers (3)

Evgeniy Labunskiy
Evgeniy Labunskiy

Reputation: 2042

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>

Upvotes: 2

Richard H
Richard H

Reputation: 39095

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.

Upvotes: 2

Mikhail
Mikhail

Reputation: 9007

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.

Upvotes: 1

Related Questions