Add simple product with ajax – twice
-
Hey there, hope you’re well..
At first. It is not possible to share a link, cause it’s a local installation.. Hope it’s nevertheless ok to ask a question here..
I write a plugin to add products with ajax to woo-cart. This works very well with variable products, but if I try it with simple products, they are added twice..
This is the shortened code, normally I use sanitizing, nonce etc. All values are grabbed right, if I check them inside the response.
This is my function for wp-ajax:
if ( substr( $_SERVER['REQUEST_URI'], 0, 6 ) === '/cart/' ) { add_action( 'wp_enqueue_scripts', function(){ wp_enqueue_script( 'shop-cart', get_stylesheet_directory_uri().'/js/shop-cart.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'shop-cart', 'php', array( 'fy_nonce' => wp_create_nonce( 'fy-nonce' ), 'fy_spinn' => admin_url( '/images/wpspin_light.gif' ), 'fy_url' => admin_url( 'admin-ajax.php' ) ) ); }); } add_action( 'wp_ajax_fy_add_to_cart', 'fy_add_to_cart' ); add_action( 'wp_ajax_nopriv_fy_add_to_cart', 'fy_add_to_cart' ); function fy_add_to_cart() { $product_id = (int) $_POST['add-to-cart']; $quantity = (int) $_POST['quantity']; if ( ! $variation_id ) { ob_start(); $response = WC()->cart->add_to_cart( $product_id, $quantity ); } echo $respond; die(); }
This is my code inside the js-file:
(function($){ $(function(){ "use strict"; $('button.single_add_to_cart_button').on('click', function(){ var data = { action: 'fy_add_to_cart', values: $theGrabbedValues, // add-to-cart, quantity etc. nonce: php.fy_nonce } $.ajax( { type: "post", url: php.fy_url, data: data, success: function(r){ resp.addClass('success').html(r); }, error: function(r){ resp.addClass('error').html(error); } }); return false; }); }); }(jQuery));
If I debug the values from $_POST inside the ajax-response, it shows me the right quantities. But if I reload the cart, everytime the product-quantity is added twice.
3 => 6, 5=> 10 and so on..
Can anybody tell me the reason for this and how to fix it?
Thanks a lot and best regards..
- The topic ‘Add simple product with ajax – twice’ is closed to new replies.