How to update session array via ajax?

浪尽此生 提交于 2020-06-23 05:23:08

问题


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);
      ?>

回答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.




回答2:


You can try this code -

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

    else{
    array_push($_SESSION['cart'],"your desired data");
    }


来源:https://stackoverflow.com/questions/32199757/how-to-update-session-array-via-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!