Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  107] [ 5]  / answers: 1 / hits: 21752  / 10 Years ago, tue, may 20, 2014, 12:00:00

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;
?>

More From » php

 Answers
7

Excellent answer by Phil, however since the OP title says




send json object from javascript (not jQuery ) to php




this is how to do it with (vanilla) javascript, in case it helps somebody looking for this method:



var jsondata;
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
var data = JSON.stringify(flickr);

var xhr = new XMLHttpRequest();
xhr.open(POST, ../phpincl/apiConnect.php, !0);
xhr.setRequestHeader(Content-Type, application/json;charset=UTF-8);
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
console.log(jsondata);
}
}


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:



header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;


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 URL



http://example.com


into



http://example.com


... which is not the case in the OP but useful in some other scenarios.


[#70941] Friday, May 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;