I'm posting 3 arrays of data to a php file(checkout.php) on the server via jquery post.
$.post("checkout.php", {items_name : JSON.stringify(items_name), items_price : JSON.stringify(items_price), items_amount : JSON.stringify(items_amount)}, function(data){
console.log(data);
//those three are arrays(items_name, items_price & items_amount
});
window.location.href = "checkout.php";
Then I receive the data arrays in the checkout.php and store them in $_SESSION.
$items_name = json_decode($_POST['items_name']);
$items_price = json_decode($_POST['items_price']);
$items_amount = json_decode($_POST['items_amount']);
session_start();
$_SESSION['items_name'] = $items_name;
$_SESSION['items_price'] = $items_price;
$_SESSION['items_amount'] = $items_amount;
When the page redirects to checkout.php after making the jquery post, when i try to access data from session, it doesn't show anything.
session_start();
print_r($_SESSION);
Where am I doing wrong?
The jQuery post
call is executed asynchronously, so your code continues down to the redirect immediately without waiting for the php script to finish on the server. Add your redirect to the success/complete callback for post
.
$.post("checkout.php", {items_name : JSON.stringify(items_name), items_price : JSON.stringify(items_price), items_amount : JSON.stringify(items_amount)}, function(data){
// whatever
window.location.href = "checkout.php";
});
checking if only $_POST is set, doesn't work. But making it more specific works.
if(isset($_POST['items_name'])){
//Code here
}
Now this works fine.