简体   繁体   中英

Not able to store ajax variables in session array

I am making a cart-mechanism with jquery , ajax and php . The problem is that the text in the html element aren't getting appended to the session array. This is my ajax code:

$(document).ready(function(){
        $("#cart").on("click", function(){
            var name = $("#name").text();
            var cost = $("#cost").text();
            $.ajax({
                type:"post",
                data:"name="+name+"&cost="+cost,
                url:"senddata.php",
                success:function(data){
                    $("#info").html(data);
                }
            }); 
        }); 
    });

This is my html displayed with php:

function getData()
{
require_once('../config.php');

$query = mysqli_query($conn, "SELECT p_name, p_cost, p_pic, p_desc FROM products");

while($row = mysqli_fetch_assoc($query))
{
    echo "<form><tr>";
    echo "<td id='name' name='name'>" . $row['p_name'] . "</td>";
    echo "<td id='cost' cost='cost'>" . $row['p_cost'] . "</td>";
    echo "<td>" . $row['p_pic'] . "</td>";
    echo "<td>" . $row['p_desc'] . "</td>";
    echo "<td id='cart'><input type='button' id='submit' value='Add To Cart'></td><tr></form>";
}

mysqli_close($conn);

}

And finally, this is where I have stored the ajax variables in a session array:

session_start();

$_SESSION['cart_name'] = array();
array_push($_SESSION['cart_name'], $_POST['name']);
var_dump($_SESSION['cart_name']);

$_SESSION['cart_cost'] = array();
array_push($_SESSION['cart_cost'], $_POST['cost']);
var_dump($_SESSION['cart_cost']);

I am getting no error whatsoever but the items get appended to the array the first time, but after that, the variables don't get appended at all.

Variables does not appended because you initialize every time the

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

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

That means that every time before you push the new data you empty the SESSION var.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM