Reputation: 35
I'm having trouble working out things with json_decode. I got a valid json that's being sent over $_POST.
Here's the JSON object that is being passed, the inventory variable:
[{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"},
{"item_name":"Brown Shoes","item_desc":"asdasd","item_type":"footwear"}]
Here's the html javascript code.
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "post" accept-charset="UTF-8">
<input type = "hidden" name = "inv" id = "inv"/>
<input type = "submit" id = "btn_save" onclick = "saveInventory()" value = "Save"/>
</form>
<script type = "text/javascript">
function saveInventory(){
var inv = document.getElementById("inv");
inv.value = inventory;
}
</script>
Here's the php script that'll fetch the json from input type hidden
<?php
if(isset($_POST['inv'])){
$inv = $_POST['inv'];
var_dump(json_decode($inv,true)); // returns NULL
}
?>
I've been reading lots of json_decode issues over the web but most of them have different issues regarding json_decode returning null. Anyone might find out what's wrong here? Thanks.
Upvotes: 1
Views: 277
Reputation: 1
<?php
if(isset($_POST['inv'])){
$json=json_decode($_POST['inv']);
foreach($json as $j){
echo "NAME: ".$j->{"item_name"};
echo "<hr/>";
}
}
?>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>">
<input type="text" name='inv' value='[{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"},{"item_name":"Brown Shoes","item_desc":"asdasd","item_type":"footwear"}]'/>
<input type="submit" value="SEND"/>
</form>
Upvotes: 0
Reputation: 64536
It appears your inventory
variable is a JavaScript array of objects, instead of a JSON string. So you need to convert it to JSON to store it in the HTML input value:
function saveInventory(){
var inv = document.getElementById("inv");
inv.value = JSON.stringify(inventory); // convert to JSON string
}
Upvotes: 1