0

I'm passing user input, which is just quantity and product code in this case to the php script to store into session array via ajax. I expect, each time user clicks submit and the ajax call is made, the quantity and product code will be added into session array. But now what happen is, each time it updates existing data in the session. So only one pair of data exist.

This is my ajax script:

<script>
      <!--display form submission result-->
      var param;
      var param2;
      var i;
      function sendToCart(param, param2){
    $("document").ready(function(){
          $("#popup-order").submit(function(){            
            var data = {
              "action": "test"
            };
            data = $(this).serialize() + "&" + $.param(data);
            $.ajax({
              type: "POST",
              dataType: "json",
              url: "addToCart.php?id="+param, //Relative or absolute path to response.php file
              data: data,
              success: function(data) {
                  console.log(data);
              }
            });
            return false;
          });
        });

      }
    </script>

my PHP sendToCart.php

   <?php
    session_start();

    $return = $_POST;  
    $return['json']= json_encode($return); 
    $data = json_decode($return['json'], true);

     $_SESSION['cart']=array();
    array_push($_SESSION['cart'], array("quantity"=>$data['qty'],"id"=>$data['id']));
    echo json_encode($cart);
      ?>

2 Answers 2

3

You can try this code -

  if(!is_array($_SESSION['cart']))
    {
      $_SESSION['cart'] = array();
    }

    else{
    array_push($_SESSION['cart'],"your desired data");
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You're overwriting the session variable every time an ajax call is made ...

$_SESSION['cart']=array();

You need to read the existing session data and add to that data.

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.