1

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?

2
  • Because you are trying to pass an array. It is possible to pass array values using class but not for id tags. Commented Sep 11, 2015 at 0:40
  • @LoganWayne Could you show me a small example of what you mean? I am still really struggling Commented Sep 11, 2015 at 18:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am a little confused - so am I adding this to my current JS?
@phpcoder yeah, you replace your cart function with this one, although the contents are just kinda the same.

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.