[ACCEPTED]-send json object from javascript to php-json

Accepted answer
Score: 11

The standard jQuery .ajax() method uses the data property 11 to create an x-www-form-urlencoded string to pass in the request 10 body. Something like this

action=Flickr&get=getPublicPhotos

Therefore, your 9 PHP script should not look for $_POST['data'] but instead, $_POST['action'] and 8 $_POST['get'].

If you want to send a raw JSON data payload 7 to PHP, then do the following...

Set the 6 AJAX contentType parameter to application/json and send a stringified version 5 of your JSON object as the data payload, eg

$.ajax({
    url: '../phpincl/apiConnect.php',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(flickrObj),
    dataType: 'json'
})

Your 4 PHP script would then read the data payload 3 from the php://input stream, eg

$json = file_get_contents('php://input');

You can then parse this 2 into a PHP object or array...

$dataObject = json_decode($json);
$dataArray = json_decode($json, true);

And, if you're 1 just wanting to echo it back to the client..

header('Content-type: application/json');

// unmodified
echo $json;

// or if you've made changes to say $dataArray
echo json_encode($dataArray);
Score: 9

Excellent answer by Phil, however since 14 the OP title says

send json object from 13 javascript (not jQuery ) to php

this is how to do it 12 with (vanilla) javascript, in case it helps 11 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 10 need to convert the server's response into 9 a javascript object using JSON.parse()

Now, on the server side 8 (based on Phil's answer) if you are sending 7 back a response to the client, you could 6 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 5 then encoding back the raw json input is 4 to properly escape slashes in (possible) URLs 3 within the data, e.g.

json_encode will convert this 2 URL

http://example.com

into

http:\/\/example.com

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

Score: 1

Use:

makeFlickrCall( { data: JSON.stringify( flickr )} );

Instead of

makeFlickrCall(flickr);

Your server-side script should 1 receive your JSON as follows:

data="{"action":"Flickr","get":"getPublicPhotos"}"

More Related questions