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){
        $.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;
?>

 Answers

76

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.

Wednesday, March 31, 2021
 
joostvandriel
answered 7 Months ago
12

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:

$('body-item').html(data.b);

From the documentation:

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

Wednesday, March 31, 2021
 
EzzDev
answered 7 Months ago
88

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>
</select>

$(function(){
    $("#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) {
                alert(result); 
            });
            //by the way $(this).val() = id1|id2|id3
        }
    });
});
Saturday, May 29, 2021
 
Amber
answered 5 Months ago
90

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()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_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.

References:
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: http://www.ietf.org/rfc/rfc4627.txt

Tuesday, June 8, 2021
 
VieStar
answered 5 Months ago
58

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

I used this code for the android part :

new Thread(new Runnable() {
        @Override
        public void run() {
            OutputStream os = null;
            InputStream is = null;
            HttpURLConnection conn = null;
            try {
                //constants
                URL url = new URL("http://192.168.43.64/happiness_barometer/php_input.php");
                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 */ );
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setFixedLengthStreamingMode(message.getBytes().length);

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

                //open
                conn.connect();

                //setup send
                os = new BufferedOutputStream(conn.getOutputStream());
                os.write(message.getBytes());
                //clean up
                os.flush();

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

                conn.disconnect();
            }
        }
    }).start();

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'};

try 
{
    $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)) {
    $sql->execute(array(
        '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
 
pamelus
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 :