3

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>
1
  • use class instead of id in your html as <a class='addtowishlist' class='link' href='#' data-data='".$rows['p_id']."'>Add to wishlist</a> and change the syntax of ajax as well . Commented Mar 1, 2016 at 3:48

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

0

use class instead of id in your html as

<a class='addtowishlist' class='link' href='#' data-data='".$rows['p_id']."'>Add to wishlist</a> 

and change the syntax of ajax as well

<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.