I have an HTML that gets its values from an array list. I’m submitting the form with Ajax and with a PHP script. The issue I’m facing is when clicking on the other array it only submits the first value array. Below is what my form looks like with the PHP loop of array listing:
index.php
$query_product = "SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare($query_product);
if($product_stmt->execute()){
while($row_product = $product_stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row_product["id"];
$title = $row_product["title"];
$description = $row_product["description"];
$price = $row_product["price"];
$img = $row_product["img"];
?>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo $id ?>" name = "id" id="id" >
<input type="hidden" value="<? echo $price; ?>" name="price" id="price">
<input type="hidden" value="<? echo $img; ?>" name="img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
<?php
}
}
?>
My Ajax looks like the below:
<script type="text/javascript">
function clickButton(){
var title = $("#title").val();
var price = $("#price").val();
var img_src = $("#img_src").val();
var id = $("#id").val();
alert(title);
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
When I tried to alert(title);
above it return just the first array value even though I click the other arrays.
2
Answers
So I was able to solve this myself by adding the ID of each item from the loop to the ID of the input form in the HTML making the ID of each item unique. Below is how I solved it:
And my Javascript is as below:
If you ignore the need for a form as you are using ajax you could streamline your code so that each record displays a single button that has various attributes set which are read by the javascript
click
handler and used to construct the payload sent via ajax to the php server.