2

I am developing an ecommerce site with angularjs.. Whenever a user add, change quantity or delete product from cart a local array of products will be updated(I am not pushing to server because that would mean a lot of requests) and I listened for window.onbeforeunload to push changes to server. It worked great on my local machine. But when I tested this on server it didn't work as expected.

Is there another way to do this? Maybe saying before leaving page wait a second to send a successful request then leave? Or do I have to push changes every time the cart is updated..

I also want to leave managing cart for the server, meaning I can't manipulate cookies. Because on server I am using external classes that handle cart on it's way e.g. creating encrypted item identifier for each item.

  • I had a similar issue. To solve it I created a system to wait for the responses to come back to the client before leaving, but honestly I don't know if it was the technical reason why my requests would not reach. It did solve the problem though. – Sebas Oct 25 '13 at 16:09
  • I found a solution [here](http://stackoverflow.com/questions/2970782/javascript-wait-until-ajax-request-finishes-to-close-page) but that would prompt user every time he tries to leave the page. Is that how you did it ? – Kareem Mohamed Oct 25 '13 at 16:20

1 Answers1

0

I found a solution, not sure if it's best practice but after testing it in many situations. It seems to work very nice...

  1. When user modifies the cart the items are saved using javascript(no requests needed) in a cookie as json array.
  2. Before each request I check if there were items saved in the cookies to do the following: a. Destroy the cart. b. Retrieve and json_decode items saved in the cookies. c. Insert these new items in the empty cart. d. Unset this cookie.

The good thing about this approach, there aren't any overhead requests to push local changes to server But the bad thing it makes using a cart on the server that saves items in different cookie look silly and I might refactor that with my own cart class to share the same items cookie ....