Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSam Chaudry
25,519 PointsPHP and AJAX
Hi guys I'm wondering if you can help? I'm trying to post data to a PHP page which I have created and it seems to be working fine i.e. it will echo the data set back. However when I try unwrapping the object on the back end it won't do it, which is weird but if anyone can help that would be awesome. I've tried using the various clean methods in PHP but even that won't work..If the object is hard coded into json_decode then it will work i.e.
// $json = '{"cop":"John Mclane","airman":"Maverick","wing":"Iceman","rock":"Rocky Balboa"}';
//$copName = json_decode($json);
//echo $copName->cop; echos John Mclane
AJAX code
var jsonObject = {}; var JSONstr;
var inputDataArray = ($(".inputData").serializeArray());
for (var i = 0; i < inputDataArray.length; i++){
jsonObject[inputDataArray[i]['name']] = inputDataArray[i]['value'];
}
var data = JSON.stringify(jsonObject);
$.ajax({
url: 'services.php',
type: 'post',
data: {"points" : JSON.stringify(data)},
success: function(data) {
// Do something with data that came back.
alert(data);
}
});
PHP
if (isset($_POST["points"])) {
$data = json_decode($_POST["points"]); // return array not object
echo $data->cop; // Won't do churn out anything.
}