Posting JSON object to remote server

I have following javascript code. I want to post some JSON data to a remote server.


var data =  {
    "country": "United States",
    "GDP": "19.39",
    "currency":{
        "code":"USD",
        "sign":"$"
   }
};

var data_string = JSON.stringify(data);

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/post.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data_string);

This fails. But if i change the data as follows, it works

var data =  {
    "country": "United States",
    "GDP": "19.39",
};

Here is content of post.php

<?php

$logFile =  __DIR__ . "/log.txt";

error_log("GOT REQUEST\n", 3, $logFile);

$msg = "";

$json_params = file_get_contents("php://input");

function isValidJSON($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
 }
 
 $json_params = file_get_contents("php://input");
 
 if (strlen($json_params) > 0) {
    if (isValidJSON($json_params)) {
        $decoded_params = json_decode($json_params);
        foreach ($decoded_params as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $msg .=  "$key = $value\n";
        }
    } else {
        $msg = $json_params;
    }

    error_log("$msg\n", 3, $logFile);
    error_log("------------------------------\n", 3, $logFile);
   
 }

Any idea it is not working ? There is no error in javascript side, on PHP script, not getting any data.

EDIT: I added a “GOT REQUEST” to PHP script. When posting, i getting request to PHP script, but no data.

Is the second call to file_get_contents() causing a problem?

I removed it, stil have problem when Json object passed have another json like structure in it {}

Here is the updated post.php code

<?php

$logFile =  __DIR__ . "/log.txt";
$msg = "";

error_log("GOT REQUEST\n", 3, $logFile);

$json_params = file_get_contents("php://input");

function isValidJSON($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
 }

if (strlen($json_params) > 0) {
    if (isValidJSON($json_params)) {
        $decoded_params = json_decode($json_params);
        foreach ($decoded_params as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $msg .=  "$key = $value\n";
        }
    } else {
        $msg = $json_params;
    }
    error_log("$msg\n", 3, $logFile);
    error_log("------------------------------\n", 3, $logFile);
}

I’m guessing (I haven’t used JSON much, if at all) that the problem is where you have those multiple entries for the currency field, they probably come out as an array. That will cause you a problem when you try to append it in its entirety. I think you’d need to use isarray() to see if $value is an array each time, and if it is, run a second nested foreach to extract the values from it. That won’t be a major issue, unless you’re intending the code to work with any level of nested arrays.

1 Like

droopsnoot is absolutely right - the problem is because your foreach loop doesn’t handle nested data.
The line $msg .= "$key = $value\n"; is expecting $value to be something it can cast to a string.

Bear in mind as well that json_decode will return data as stdClass object by default. If you want it to return associative arrays, you have to pass true as the second argument: json_decode($json_params, true);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.