Irfan Sindhi
Irfan Sindhi

Reputation: 75

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.

Upvotes: 0

Views: 165

Answers (1)

AlexCode
AlexCode

Reputation: 653

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.

Upvotes: 3

Related Questions