Asked  7 Months ago    Answers:  5   Viewed   35 times

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){
            url: '../phpincl/apiConnect.php',
            type: 'POST',
            data: flickrObj
        .done(function(data) {
        .fail(function() {
        .always(function() {


PHP file

    $obj = $_POST['data'];
    // print_r($obj);
    return $obj;



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();"POST", "../phpincl/apiConnect.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // in case we reply back from server
        jsondata = JSON.parse(xhr.responseText);

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;


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


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

Wednesday, March 31, 2021
answered 7 Months ago

When you use dataType: 'json', jQuery calls JSON.parse() and puts the result in data. You shouldn't call it yourself, since data is not a JSON string, it's the parsed object. So just do:


From the documentation:

"json": Evaluates the response as JSON and returns a JavaScript object.

Wednesday, March 31, 2021
answered 7 Months ago

So, I have corrected your errors and you should have the below for it to work with no errors, unless there is something else that is causing errors.

<select id='catlist' name='catlist'>
    <option value='NA'>Select Category</option>
    <option value='id1'>val1</option>
    <option value='id2'>val2</option>
    <option value='id3'>val3</option>

    $("#catlist").change(function() {
        var sVal = $(this).val();
        if (sVal !== "NA") { // I am assuming you don't want to make an ajax call when the value is 'NA'!
            $.getJSON("ajax.php", {catid: $(this).val()}, function(result) {
            //by the way $(this).val() = id1|id2|id3
Saturday, May 29, 2021
answered 5 Months ago

I've gotten lots of information here so I wanted to post a solution I discovered.

The problem: Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it.

Environment: Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu.

What works (version 1):
1) JSON is just text. Text in a certain format, but just a text string.

2) In Javascript, var str_json = JSON.stringify(myObject) gives me the JSON string.

3) I use the AJAX XMLHttpRequest object in Javascript to send data to the server:

request= new XMLHttpRequest()"POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
[... code to display response ...]

4) On the server, PHP code to read the JSON string:

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

This reads the raw POST data. $str_json now contains the exact JSON string from the browser.

What works (version 2):
1) If I want to use the "application/x-www-form-urlencoded" request header, I need to create a standard POST string of "x=y&a=b[etc]" so that when PHP gets it, it can put it in the $_POST associative array. So, in Javascript in the browser:

var str_json = "json_string=" + (JSON.stringify(myObject))

PHP will now be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest as in version 1 above.

Displaying the contents of $_POST['json_string'] will display the JSON string. Using json_decode() on the $_POST array element with the json string will correctly decode that data and put it in an array/object.

The pitfall I ran into:
Initially, I tried to send the JSON string with the header of application/x-www-form-urlencoded and then tried to immediately read it out of the $_POST array in PHP. The $_POST array was always empty. That's because it is expecting data of the form yval=xval&[rinse_and_repeat]. It found no such data, only the JSON string, and it simply threw it away. I examined the request headers, and the POST data was being sent correctly.

Similarly, if I use the application/json header, I again cannot access the sent data via the $_POST array. If you want to use the application/json content-type header, then you must access the raw POST data in PHP, via php://input, not with $_POST.

1) How to access POST data in PHP: How to access POST data in PHP?
2) Details on the application/json type, with some sample objects which can be converted to JSON strings and sent to the server:

Tuesday, June 8, 2021
answered 5 Months ago

Finally, I success to send a JSONObject to my server.

I used this code for the android part :

new Thread(new Runnable() {
        public void run() {
            OutputStream os = null;
            InputStream is = null;
            HttpURLConnection conn = null;
            try {
                URL url = new URL("");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("rate", "1");
                jsonObject.put("comment", "OK");
                jsonObject.put("category", "pro");
                jsonObject.put("day", "19");
                jsonObject.put("month", "8");
                jsonObject.put("year", "2015");
                jsonObject.put("hour", "16");
                jsonObject.put("minute", "41");
                jsonObject.put("day_of_week", "3");
                jsonObject.put("week", "34");
                jsonObject.put("rate_number", "1");
                String message = jsonObject.toString();

                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout( 10000 /*milliseconds*/ );
                conn.setConnectTimeout( 15000 /* milliseconds */ );

                //make some HTTP header nicety
                conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");


                //setup send
                os = new BufferedOutputStream(conn.getOutputStream());
                //clean up

                //do somehting with response
                is = conn.getInputStream();
                //String contentAsString = readIt(is,len);
            } catch (IOException e) {
            } catch (JSONException e) {
            } finally {
                //clean up
                try {
                } catch (IOException e) {


and this one in the php part :

$json = file_get_contents('php://input');
$obj = json_decode($json);
$rate = $obj->{'rate'};
$comment = $obj->{'comment'};
$category = $obj->{'category'};
$day = $obj->{'day'};
$month = $obj->{'month'};
$year = $obj->{'year'};
$hour = $obj->{'hour'};
$minute = $obj->{'minute'};
$day_of_week = $obj->{'day_of_week'};
$week = $obj->{'week'};
$rate_number = $obj->{'rate_number'};

    $bdd = new PDO('mysql:host=localhost;dbname=happiness_barometer;charset=utf8', 'utilisateur', '');
} catch (Exception $e) 
    die('Erreur : '.$e->getMessage());

$sql = $bdd->prepare(
'INSERT INTO rates (rate, comment, category, day, month, year, hour, minute, day_of_week, week, rate_number) 
VALUES (:rate, :comment, :category, :day, :month, :year, :hour, :minute, :day_of_week, :week, :rate_number)');
if (!empty($rate)) {
        'rate' => $rate,
        'comment' => $comment,
        'category' => $category,
        'day' => $day,
        'month' => $month,
        'year' => $year,
        'hour' => $hour,
        'minute' => $minute,
        'day_of_week' => $day_of_week,
        'week' => $week,
        'rate_number' => $rate_number));

Hope it will help someone else ;)

Thursday, July 1, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :