Reputation: 131
I am sending JSON formatted data using ajax post request, and I want to retrieve the data from the file that data was sent to. If you do not know how many objects are in a JSON variable and you do not know the keys, how can you retrieve the data using $_POST["name"]; ?
The website I am currently working on is like a simple online store, and the customer can choose any items however many times. I am for now storing the date in localStorage. The JSON data will be like {"itemName":"item's name", "number": "the number of the items they want"}, and it cannot be expected how many different items the customer buys. When placeOrder button is pressed, I want to send the purchase information in JSON format, and I want to parse it in php file.
$(document).ready(function(){
$(".placeOrder").click(function(){
var purchaseInfo = {}; //make JSON formatted variable
var key, item;
//move all localStorage data (which contains the item and the number)
//to purchaseInfo
for(var i=0; i<localStorage.length; i++){
key = localStorage.key(i);
item = localStorage.getItem(key);
purchaseInfo[key] = item;
}
//ADDED THIS CODE
purchaseInfo = {"productPurchased":purchaseInfo};
//send the data to place_order.php
$.ajax({
url: "place_order.php",
data: purchaseInfo,
method: "POST",
success: function(data){
alert("success");
//change the page using location.href
window.location.href = "place_order.php";
},
error: function(data){
alert("failed");
}
});
});
});
After sending purchaseInfo varibale to place_order.php, I am not sure how to parse the content of the variable.. Could anyone help me get the idea here? Thank you very much in advance.
EDIT: The ajax function and how I (tried to) move the data of localStorage to a variable purchaseInfo in JSON format, are shown above.
In place_order.php (where I am trying to retrieve the JSON data and compute more so I can calculate the total price)
<?php
//this line below prints NULL
var_dump($_POST["productPurchased"]);
//and this code below prints "I am empty"
if("" == trim($_POST["productPurchased"])){
echo "I am empty";
}else{
echo "I am filled";
}
//$purchaseInfo = $_POST['productPurchased'];
//the below line of code prints "array(0) { } "
var_dump($_POST);
?>
Upvotes: 0
Views: 2177
Reputation: 2464
In JavaScript:
purchaseInfo = {'purchaseInfo': purchaseInfo};
$.ajax({ ...
In PHP:
$purchaseInfo = $_POST['purchaseInfo'];
// Do smth with data in $purchaseInfo
Now in PHP $purchaseInfo
is an associative array with items from localStorage.
Upvotes: 2