Reputation: 5455
I have problem here, I need all the stuffs inside this $_SESSION['cart']
thing
and pass it to jQuery to use it in a php-ajax file, my question is, how to do that?
Here's what I have in mind
function myfunc()
{
//save cart to db of logged user
$("a.savecart").click(function(){
//how to assign the $_SESSION['cart'] into a js variable ?
$.ajax({
type: "POST",
url: "classes/ajax.cart.php",
data: //what to put here ?
success: function(data){
alert(data);
location.reload();
}
});
return false;
}
});
}
Upvotes: 1
Views: 828
Reputation: 160833
Just echo it like below (just example):
data: {"cart_id" : <?php echo $_SESSION['cart']; ?>},
Or if your $_SESSION['cart']
is an associative array, you can use json_encode
function.
data: <?php echo json_encode($_SESSION['cart']); ?>,
EDIT:
For example, if your $_SESSION['cart']
is an array like below:
array(
'id' => 111;
'num' => 222;
//etc...
)
Then in your php ajax part, you could get the data by $_POST['id']
and $_POST['num']
etc...
Upvotes: 1
Reputation: 2624
Use json. If you have php > 5.2 on your server you can use json_decode and json_encode functions, see at manual. In data parameter you can use these trick:
data: 'jsondata={"some_key":"' + some_var + '"}'
attention you should use double quotes in key and value pair. So when it comes to script you can do that:
json_decode($_POST['jsondata']);
Upvotes: 0
Reputation: 2236
I need all the stuffs inside this $_SESSION['cart'] thing and pass it to jquery to use it in a php-ajax file,
If the data you need is in session, then you can send empty ajax call and use $_SESSION['cart']. No need to pass it again.
OR
You can assign the value to a hidden field and use it in jquery as -
data: $("#session_value").val(),
Upvotes: 0