I’m building a process where js object gets submitted to a php file via ajax (POST and json type) and I’m having problem iterating through what’s been submitted in php.
My object looks like this:
var myObject = {
"section1":{
"subitem1":"value1",
"subitem2":"value2"
},
"section2":{
"subitem3":"value3",
"subitem4":"value4"
}
}
My ajax looks like this:
$.ajax({
url:"test.php?section=section2",
type:"POST",
dataType:"json",
success:function(data){
// what i do with the response data
},
data:myObject
});
Here’s my php:
$section = $_GET['section'];
$json = json_decode($_POST[$section], true);
foreach($json as $key=>$value){
//if this iteration works here, it'll be the happiest point of my day
}
Now, in the php above, if i refer to the certain section as $_POST[‘section2’], then iteration does work. So using PHP’s variables variable seems to be the issue but i don’t know….Whole $_POST also seems to come in as an object. DOES JQUERY AJAX automatically do JSON.stringify on the object that i’m submitting? I’ve tried using stringify but it didnt work.. i have latest version of chrome…
Also, I tried using json_decode on the $_POST too… still $_POST[$section] gets interpreted as null…
Any help, suggestion, advice is greatly appreciated!!
That’s not going to what you think, stringify the object and send it as part of a key/value pair and then decode it from the post field.