Why my ajax can get data only first item in while loop?
Example : First add to wishlist with first item in loop product id = 64, When I add another item product id is always 64.
My Code :
<a id='addtowishlist' class='link' href='#' data-data='".$rows['p_id']."'>Add to wishlist</a>
<script type="text/javascript">
$(document).ready(function(){
$("#addtowishlist").live('click', function(evt) {
var link_data = $('.link').data('data');
$.ajax({
type: "POST",
url: 'addtowishlist.php',
data: ({product_id: link_data}),
success: function(data) {
alert(data);
}
});
});
});
</script>
ID must be unique. Otherwise use class instead. If you're using the same name for ID, only first matched data returned. Try following code:
This should be defined as a class (remove id attribute) :
<a class='addtowishlist link' href='#' data-data='".$rows['p_id']."'>Add to wishlist</a>
And this :
<script type="text/javascript">
$(document).ready(function(){
// use class selector instead of ID
$(".addtowishlist").live('click', function(evt) {
// take only current clicked data element
var link_data = $(this).data('data');
$.ajax({
type: "POST",
url: 'addtowishlist.php',
data: ({product_id: link_data}),
success: function(data) {
alert(data);
}
});
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With