I am trying to send JSON object from Javascript/Jquery to PHP and I am getting and error msg in my console. What am I doing wrong. I am new to JS and PHP.
JQuery file:
$(document).ready(function() {
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
// console.log(typeof(flickr));
var makeFlickrCall = function(flickrObj){
$.ajax({
url: '../phpincl/apiConnect.php',
type: 'POST',
data: flickrObj
})
.done(function(data) {
console.log("success");
console.log(JSON.stringify(data));
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
};
makeFlickrCall(flickr);
});
PHP file
<?php
$obj = $_POST['data'];
// print_r($obj);
return $obj;
?>
Excellent answer by Phil, however since the OP title says
this is how to do it with (vanilla) javascript, in case it helps somebody looking for this method:
Notice we still need to convert the server's response into a javascript object using
JSON.parse()
Now, on the server side (based on Phil's answer) if you are sending back a response to the client, you could do:
NOTE:
The reason behind decoding first and then encoding back the raw json input is to properly escape slashes in (possible) URLs within the data, e.g.
json_encode
will convert this URLinto
... which is not the case in the OP but useful in some other scenarios.