PhpDude
PhpDude

Reputation: 1600

Add to cart adding first item

I have a simple cart where I can add items on the fly and it update via AJAX. Issue being I am pulling my items from the database but when I click 'add to cart' it populates the cart but with the first item only so no matter which one I click it adds item 1.

I am looping through a result and getting the row:

    while ($row = mysqli_fetch_array($r)) {

    echo '
    <div class="items" id="item">
    <a href="doc_view.php?prod_id='.$row["prod_id"].'"> '.$row["prod_name"]. '</a>';

    echo "
    <div class='product_display'>
    <p><img src='../admin/uploads/".$row['file_upload']."'></p>";    


   echo"
    <input type='button' value='Add To CART' onclick='cart(\"item\");' "; 

    echo'
    <p>Price - '.$row["prod_price"]. '</p>
    <input type="hidden" id="item_name" value="'.$row["prod_name"]. '">
    <input type="hidden" id="item_price" value="'.$row["prod_price"]. '">';?>

    <?php echo'
    </div>
    </div>
    ';


    } 

The echo's really need cleaning up but they confuse me so much!

I am using a little bit of JS to do the AJAX:

$(document).ready(function(){

  $.ajax({
    type:'post',
    url:'store_items.php',
    data:{
      total_cart_items:"totalitems"
    },
    success:function(response) {
      document.getElementById("total_items").value=response;
    }
  });

});

And my JS does the rest:

    function cart(id)
    {
    var ele=document.getElementById(id);
    var img_src=ele.getElementsByTagName("img")[0].src;
    var name=document.getElementById(id+"_name").value;
    var price=document.getElementById(id+"_price").value;

    $.ajax({
        type:'post',
        url:'store_items.php',
        data:{
          item_src:img_src,
          item_name:name,
          item_price:price
        },
        success:function(response) {
          document.getElementById("total_items").value=response;
        }
      });

    }

    function show_cart()
    {
      $.ajax({
      type:'post',
      url:'store_items.php',
      data:{
        showcart:"cart"
      },
      success:function(response) {
        document.getElementById("mycart").innerHTML=response;
        $("#mycart").slideToggle();
      }
     });

    }

I thought I would share it all so you can see - but the main issue is the fact it just adds item 1 form the list no matter which one you click on - I am getting no errors and the console is giving me nothing?

Upvotes: 1

Views: 861

Answers (1)

Arnelle Balane
Arnelle Balane

Reputation: 5487

It is because you are using the same id for all your items. IDs should only be used once per page, and in cases where you are using it multiple times, document.getElementById(id) will only get the first one that it finds which is why you keep on getting the first item in the list only.

You can give each item different ids and pass that id to the cart function. Or to make things simplier, use event delegation (since you're already using jQuery) to listen for clicks on the Add To Cart button so that you don't have to use the onclick attribute anymore. You can do it like this:

$(document).on('click', 'ADDTOCARTBUTTONSELECTOR', function() {
    var element = $(this).closest('.items');
    var image = element.find('img')[0].src;
    var name = element.find('NAMESELECTOR').val();
    var price=document.find('PRICESELECTOR').val();

    // the ajax part follows here
});

The ADDTOCARTBUTTONSELECTOR, NAMESELECTOR, and PRICESELECTOR are just placeholders to the actual selectors to those elements, and just replace them appropriately to select the proper elements.

Upvotes: 1

Related Questions