Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax get data only first item in while loop

Tags:

jquery

ajax

php

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>
like image 370
Vintage Beef Avatar asked Mar 22 '26 04:03

Vintage Beef


1 Answers

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>
like image 169
Norlihazmey Ghazali Avatar answered Mar 24 '26 17:03

Norlihazmey Ghazali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!