![]() |
Solution to cart_update with Ajax - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21) +--- Thread: Solution to cart_update with Ajax (/showthread.php?tid=35790) |
Solution to cart_update with Ajax - El Forum - 11-11-2010 [eluser]PeterGreffen[/eluser] I followed the (rather good) tutorial on nettuts how-to-build-a-shopping-cart-using-codeigniter-and-jquery and everything works fine. The codeigniter Cart class does exactly what it is supposed to do. In the tutorial, an Ajax post is used to add a product to a cart, but for updating, it uses a redirect, so the page is entirely refreshed after a product update. I wanted only the shopping cart to be refreshed, so here's how I did that. I made this modification in the application/controllers/cart.php function add_cart_item: Code: function add_cart_item(){ In my view file, I don't display the shopping cart table as suggested in the tutorial, but I include a view file showing the contents of the cart. It is this part (and only this part) that will be refreshed after the update of a product. So this is how it looks in the view of an e.g. product details page: Code: <div id="cart_content"> And here is the shop/view-cart.php that is included: Code: <div id="update_cart"> And the add this two Ajax calls in the view-cart: 1. on submitting the first form (called #cartform), we first post to the function add_cart_item() and if that is succesfull, we imediatelly get the updated cart with cart/show_cart: Code: $("#cartform form").submit(function() { 2. We do a similar thing for the update_cart(): first post to cart/update_cart, and then directly load the updated cart with cart/show_cart, to have the updated cart without refreshing: Code: $(function(){ note: both functions go in the document.ready function on top of the view-cart.php Code: $(document).ready(function() { The cart Controller functions (basically the same as in the original tutorial): Code: function add_cart_item(){ The functions validate_add_cart and validate_update_cart are also identical to the original tutorial. I hope it can help someone out there... (BTW, I'm a designer, not a coder, so forgive me if my coding is not perfect...) P. |