I'm an absolute beginner in using javascript and ajax and that's why I'm stuck now. I have a while loop in which there are 2 different buttons. Both work, as I imagine, except for one little thing ...
The product-id
is always passed only for the first element or, if I change it for the last element.
How can I pass the correct product ID to the script?
This is my PHP file:
<?php while ( $product = $browse->fetch( PDO::FETCH_ASSOC ) ) :
$postid = $product[ 'id' ];
$userid = 1; ?>
<div id="content_<?php echo $postid ?>">
<div id="reload_<?php echo $postid ?>" class="row postfarbe browse">
<form method='post' action="" onsubmit="return add();">
<input type="hidden" id="userid" value="<?php echo $userid ?>" class="input-box">
<input type="hidden" id="productid" value="<?php echo $postid ?>" class="input-box">
<input type="hidden" id="collection" value="1" class="input-box">
<input type="hidden" id="wish" value="0" class="input-box">
<input type="submit" id="submit" value="Add to Collection" class="btn my-2 my-sm-0 btn-outline-dark btn-sm">
</form>
</div>
</div>
<?php endwhile; ?>
My Javascript is:
function add()
{
var userid = document.getElementById("userid").value;
var productid = document.getElementById("productid").value;
var collection = document.getElementById("collection").value;
var wishlist = document.getElementById("wish").value;
if(userid && productid && collection && wishlist) {
$.ajax
({
type: 'post',
url: 'post_collection.php',
data: {
user_id:userid,
product_id:productid,
collection_id:collection,
wishlist_id:wishlist
},
success: function (response) {
$("#content_"+ productid).load(" #reload_" + productid);
}
});
}
return false;
}
</script>
I know that the product id in my example is always the same, but how can I pass the correct one to the script if there are 10 or more entries in the loop?