I am looking to use AJAX to submit multiple forms on submit. I need to get the value of a hidden field to use in the AJAX call. I have the first submit working just fine and returns the response expected.
example:
<form name="add_to_cart-12345" action="add_product" method="post">
<input type="hidden" name="products_id" value="12345" />
<input class="quantity" id="product_quantity" min="1" name="cart_quantity" value="1" step="1" type="number">
<input type="submit" class="add-to-cart" value="Add to Cart" id="addProduct-12345" />
This code can repeat 1 to n times with the values 12345 changing and being unique.
My Javascript is:
<script>
$(function() { // begin document ready
$('#addProduct').on('click', function(e) {
e.preventDefault();
var cart_quantity = document.getElementById('product_quantity').value;
var products_id = parseInt(document.getElementsByName('products_id').value);
var form = $(this).closest('form');
// AJAX request
$.ajax({
url: 'ajax_add_product.php',
type: 'POST',
dataType : "html",
data: {cart_quantity, products_id},
success: function(response){
console.log(response)
var TotalInCart = parseInt(document.getElementById('cartTotal').innerText);
var cartQuantity = parseInt(document.getElementById('product_quantity').value);
var headerTotal = cartQuantity + TotalInCart;
$("#cartTotal").html(headerTotal);
$("#cartProducts").html(response);
$("#ShoppingCartModal").modal({show:true});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
$( document ).ajaxError(function() {
$( ".log" ).text( "Triggered ajaxError handler." );
});
});
</script>
What I need to do is to be able to submit any form when clicked. And push the product id, product quantity to the AJAX call.