Reputation: 793
I've created a shopping cart which works well.
Im having a problem clearing the cart, i want to use javascript to do this.
I want to use a button so when pressed it asks the user to confirm if they want to clear it, and if ok is pressed it is cleared.
So i have created the php code to clear my cart:
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
unset($_SESSION["cart_array"]);
And when this is assigned to a link it clears the cart. For example:
<a href="cart.php?cmd=emptycart">Empty Cart</a>
However i want to change this to a button.
So far i have the following javascript code to give the validation but does not clear the cart.
<script language="javascript">
function clear_cart(){
if(confirm('Shopping cart will be cleared. Continue?')){
document.form1.command.value='emptycart';
document.form1.submit();
}
}
</script>
The button:
<input type="button" value="Clear Cart" onclick="clear_cart()">
So my question is how do i get this to clear using this button and with the use of javascript or AJAX.
Thanks!
Upvotes: 0
Views: 2456
Reputation: 765
You are over complicating things.
<form method="get" action="">
<input type="hidden" name="cmd" value="emptycart" />
<input type="submit" name="empty_cart_submit" value="Empty Cart" onclick="return confirm('are you sure?');" />
</form>
For a solution without a page reload:
From your main page you want to call a script to unset the $_SESSION
, but rather than reload the page you can use ajax to reload only the cart itself.
Say you have a file which is a sub-view just for the contents of the cart, called in your main page like
<div id="cart-contents">
//with a function
<?php echo get_cart_sub_view(); ?>
//or with an inlude
<?php include('cart_sub_view.php'); ?>
</div>
You can ajax in your new cart contents using jQuery load.
You need a script to generate the html that goes inside the cart, which you can call via ajax (i.e cart_sub_view.php).
After the $_SESSION
unset call, call
$("#cart-contents").load(
'cart_sub_view.php'
);
Which will ajax to the sub view page, and then copy its contents into the cart-contents div.
Upvotes: 0
Reputation: 870
This can easily be done with jQuery and AJAX.
function clear_cart( ) {
if( confirm( 'Shopping cart will be cleared. Continue?' ) ) {
$.get( "cart.php?cmd=emptycart", function( data ) {
alert( "Cart has been cleared!" );
});
}
}
More information on .get() is here: https://api.jquery.com/jQuery.get/
If you prefer to not use jQuery, this might help: http://blog.mgechev.com/2011/07/21/ajax-jquery-beginners/
Upvotes: 1