I have dynamic list of item from database. I generate the list using the while loop and echo it inside php. The problem is the jQuery somehow only recognize the first item eventhough I click on the second item. I want to remove the clicked item directly after the ajax call is success.
this is my PHP code
while ($rowresult = mysqli_fetch_array($result)){
$id = $rowresult['id'];
$name = $rowresult['name'];
$brand= $rowresult['brand'];
$price = $rowresult['price'];
$qty = $rowresult['itemQuantity'];
$desc = $rowresult['description'];
$img = $rowresult['itemImage'];
echo "<div class=\"col-md-12\">";
echo "<div id=\"cartHeader\" class=\"rowresult cartInfo\">";
echo "<div class=\"col-md-12\">";
echo "<input type=\"text\" id=\"idValue\" name=\"idValue\" value=\" $id \"/>";
echo "<span class=\"remove\"><a href=\"#\" class=\"removeAnchor\">×</a></span>";
echo "<p> $brand $name </p>";
echo "<div class=\"col-md-4\">";
echo "<img src=\"$img\" alt=\"Product Image\" width=\"50px\" height=\"50px\"></a>";
echo "</div>";
echo "<div class=\"col-md-8\">";
echo "<span class=\"cartDesc\"> $desc </span> <br>";
echo "<strong><span class=\"cartDesc\"> RM$price </span></strong>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
and this is my jQuery code
$(".removeAnchor").click(function(event){
event.preventDefault();
var itemID = $('#idValue').val();
var self = $(this);
$.ajax({
type: 'POST',
url: 'delete_item.php',
data: {itemID:itemID},
success: function(data){
$("#cartHeader").css({"background" : "red"});
console.log(itemID);
}
});
});
this is my delete_item.php
<?php
$title = "Item Details";
session_start();
include "config.php";
$itemID = $_POST['itemID'];
?>
P.S. I am also using bootstrap
Can somebody tell me how come when I click item that is from 1st row onward will still return value that is belong to 1st item?
ANy help given is highly appreciated
The quick and dirty way to fix the problem is:
var itemID = $(this).parent().find("#idValue").val();
Generally you should try keeping id
attribute values unique accros much wider scope then just the element's parent.