Reputation: 7068
I'm trying to use JQuery to pass a data structure that looks similar to the one below to a php script:
{
"shopping":
[
{
"type": "online",
"mood": 9
},
{
"type": "mood",
"mood": 4
}
],
"researching":
[
{
"type": "online",
"mood": 3
},
{
"type": "library",
"mood": 1
}
]
}
This data in the JSON changes based on forms and sliders a user manipulates, and then the JSON is sent asynchrounously with a submit button. I am having trouble figuring out how to use JQuery to submit this request, and how to have PHP parse it. I would like to send this data using the POST method. Right now, I'm using:
$.post('server/dataInput.php',submissions, function(data){
console.log(data);
});
Where submissions is the JSON object, however this doesn't seem to be working. I also dont' know how I would then parse this JSON on PHP's end.
Upvotes: 1
Views: 1488
Reputation: 1715
If you are using jquery 1.4.0+ json_decode
is not necessary. Your data will be received in PHP as an array.
Example:
JS fragment:
var testData = {
"shopping": [
{
"type": "online",
"mood": 9
},
{
"type": "mood",
"mood": 4
}
],
"researching": [
{
"type": "online",
"mood": 3
},
{
"type": "library",
"mood": 1
}
]
};
function sendTest() {
$.post('test.php', testData, function(data) { console.log(data); });
}
Call sendTest
...
test.php:
<?php
var_dump($_POST);
And your success function will display what test.php
outputted:
array(2)
{
["shopping"]=> array(2)
{
[0]=> array(2)
{
["type"]=> string(6) "online"
["mood"]=> string(1) "9"
}
[1]=> array(2)
{
["type"]=> string(4) "mood"
["mood"]=> string(1) "4"
}
}
["researching"]=> array(2)
{
[0]=> array(2)
{
["type"]=> string(6) "online"
["mood"]=> string(1) "3"
}
[1]=> array(2)
{
["type"]=> string(7) "library"
["mood"]=> string(1) "1"
}
}
}
So, everything works out-of-the-box! :)
Upvotes: 6