I'm making an AJAX request and sending along some JSON:
$(function() {
var json = [{"id":"1", "area":"south"}, {"id":"2", "area":"north"},{"id":"3", "name":"east"},{"id":"1", "name":"west"}];
jQuery.ajax({
url: "index.php",
type: "POST",
data: {areas: JSON.stringify(json) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert(result);
}
});
and then I'm trying to use json_decode on the other end to decode it in to something useful for PHP:
<?php
if(isset($_POST['areas'])) {
$json = $_POST['areas'];
$obj = json_decode($json);
var_dump($obj);
exit;
}
?>
The AJAX post gets made fine and if I put an echo inside the if(isset$_POST) I get it back so it seems it's getting sent. But I only get Null returned from the code. Can anyone see what I'm missing?
$_POST['area']variable in your PHP script (without running its value throughjson_decode())?[]in thenameattributes for a form to create an array. It appears as though the issue is that you are trying to create an object from an object (you tried to do too much!).print_r($_POST['areas'])you get the structure you want, just don't do anything to it, remove the$obj = json_decodE($json);line or change it to$obj = $_POST['areas'].