问题
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