1

I have a session array $_SESSION['cart']['id'] and want to display each item in $_SESSION['cart]['id'] that consist of product_name and product_price value. How can I display it to html

<div class="col-md-3" id="cart">
        <div class="col-md-2">
          <p class="product-name"></p>
        </div>
        <div class="col-md-1">
          <p class="product-price"></p>
        </div>
        <form method="POST" action="">
          <button class="btn btn-primary" name="clear">Clear Cart</button>
        </form>
      </div>

jquery

$('a').on('click', function(e){
    var id = $(this).data('product-id');
    var btn_content = $(this);

    btn_content.html('Added');

    $.ajax({
      url: 'cart.php',
      type: 'POST',
      dataType: 'json',
      data: {id: id},
      success: function(products){
        $('p.product-name').html(products['product-name']);
        $('p.product-price').html(products['product-price']);
        console.log(products);
      }
    });
    e.preventDefault();
  });

this is the cart.php file

<?php session_start() ?>
<?php require 'config.php' ?>
<?php 
  if (isset($_POST['id'])) {
    $id = $_POST['id'];
    $sql = "SELECT product_name, product_price FROM products WHERE id=".$id;    
    $result = $mysqli->query($sql) or die($mysqli->error);


    $result = $result->fetch_assoc();

    //$_SESSION['cart'] = array();
    if (isset($_SESSION['cart'])) {
        if (isset($_SESSION['cart'][$id])) {
            unset($_SESSION['cart'][$id]);
        }
    }

    $_SESSION['cart'][$id] = $result;
    $cart = json_encode($_SESSION['cart']);
    echo $cart;
    }?>

I cant display all the objects in the $_SESSION['cart']. i can't figure out how to display the data to html

PHP.Newbie
  • 195
  • 1
  • 4
  • 16
  • 1
    add the php code too – roullie Nov 24 '15 at 07:46
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Nov 24 '15 at 08:20
  • Stop looking at the two ends of the problem and see how it looks in the middle. What does the resulting JSON actually look like? Does the success function fire at all? What do you get when you `console.log(products)`, does `products['product-name']` have an actual value? – Quentin Nov 24 '15 at 08:21
  • when i conlose.log(products) i get an object consisting of product_name: and product_price. and when i console.log(products['product-name']) it says product_name is undefined – PHP.Newbie Nov 24 '15 at 08:28
  • @PHP.Newbie — No, it says that `product-name` is undefined, it says nothing about `product_name` because you weren't testing for that. – Quentin Nov 24 '15 at 08:57

0 Answers0