ToyotaMR2
ToyotaMR2

Reputation: 141

Php session shopping cart array loop of inputs

I have a shopping cart I have an array of inputs with a class name. I am trying to post the data into a session array and print out the result of the array. I have this working fine. The problem is I can only ever seem to get it to return the current selected item into the array and return the array. The next selected item replaces the last item.

<?php session_start();?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


//This will echo out the sessions in the array but instead it only ever displays one. 
  <?php 

echo "Number of Items in the cart = ".sizeof($_SESSION['cart'])." <a href=cart-remove-all.php>Remove all</a><br>";

while (list ($key, $val) = each ($_SESSION['cart'])) { 
echo "$key -> $val <br>"; 
}
    ?>

<?php 

$myarray = array('Test phone 1','Test phone 2','Test phone 3'); 

foreach($myarray as $data)
{

 ?>
 <form method="post">
<div class = "container well">

<div class = "ProductTitle">
<?php echo $data; ?>
</div>

<input class="Product" type="text" name="Title"/>   
<button class = "btn btn-success" type="button" > Add</button>

</div>

 <?php

}
?>

</form>

<!-- This posts the data to the php file -->

<script type="text/javascript">

$(document).ready(function(){
   //Important for -1 as insures the current index is set to zero 


$( ".btn-success" ).click(function() {
    var x = $(this).parent().index();

var Productdata =   $('.Product').eq(x).val();


                $.ajax({
         url: 'display-data.php',
         type: 'POST',
         data: {Phonetitleclicked:Productdata}, // it will serialize the form data
                dataType: 'html'
            })
            .done(function(data){



            })


});



})
</script>
<!-- Below is the php file adding the sessions into the array -->

<?php /
 $_SESSION['cart'] = array();

  $cart_row = array(
        'product_Title'=>$_POST['Phonetitleclicked']
    );

   $_SESSION["cart"][]=$_POST['Phonetitleclicked'];
print_r($_SESSION);
 ?>

Upvotes: 0

Views: 703

Answers (1)

MatejG
MatejG

Reputation: 1423

You are always creating new array which is overwriting your old data, when pushing new item to your cart. You need to create new array only if it's not set yet:

// Your file where you are adding items
if(!isset($_SESSION['cart'])) {
  $_SESSION['cart'] = array();
}

Upvotes: 1

Related Questions