0

I'm new to PHP,JSON,js.

I have a js program that will send JSON string to PHP I have some problem when using the json_decode fn inside PHP.
I try to save the string receive from JS into a file, and the json string is correct without any problem. But when i try to use json_decode, the function hang (i think, since anything below the function call are not called at all, all my echo/print did not give anything.

Below is my js code:

function post()
{
  var test1 = {
    name:"marzzuq",
    age:16
  };
  myjson = JSON.stringify(test1);
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST","post.php",true);
  xmlhttp.setRequestHeader("Content-type","application/json");
  xmlhttp.send(myjson);
  console.log("\nsend ok: " + myjson);
}

and below is my php script:

<?php
 $rawdata = file_get_contents('php://input');
 file_put_contents('/tmp/test.json', $rawdata);
 $jsson = json_decode($rawdata);
 file_put_contents('/tmp/test3.json', $jsson);
 `echo test >> /tmp/test.txt`;
 ?>

I have tried to use htmlentities and html_entity_decode:
$result= htmlentities((string)$rawdata);
$result2 = html_entity_decode((string)$rawdata);

and use the result on json_decode but it does not work.
the length fr $rawdata is 27 (using strlen), which is correct.

I try to print the json_last_error, but like i say, all the code below the line json_decode stop working, so nothing will get print.

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        `echo ' - No errors' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_DEPTH:
        `echo ' - Maximum stack depth exceeded' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_STATE_MISMATCH:
        `echo ' - Underflow or the modes mismatch' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_CTRL_CHAR:
        `echo ' - Unexpected control character found' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_SYNTAX:
        `echo ' - Syntax error, malformed JSON' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_UTF8:
        `echo ' - Malformed UTF-8 characters, possibly incorrectly encoded' >> /tmp/test.txt`;
    break;
    default:
        `echo ' - Unknown error' >> /tmp/test.txt`;
    break;
}

Can anyone help me?

maximran
  • 425
  • 4
  • 11
  • @marekful: i see. But even if i remove that line, anything below the json_decode still not working. i have tries printing something like this: `echo yes sucess >> /tmp/test.txt`; after the json_decode but it does not print – maximran Jan 23 '18 at 04:02
  • I already gave you a detailed example about how to do this over here: https://stackoverflow.com/questions/48374719/php-receive-unquote-json-string-from-js but you ignored it. – But those new buttons though.. Jan 25 '18 at 06:27
  • Possible duplicate of [PHP receive unquote json string from js](https://stackoverflow.com/questions/48374719/php-receive-unquote-json-string-from-js) – But those new buttons though.. Jan 25 '18 at 06:27
  • @billynoah I have try your method, but maybe i did something wrong, as it is not working. I will try it again. Thanks. btw did you delete your comment on y another question? – maximran Jan 29 '18 at 03:54

2 Answers2

0

This is how I decode JSON in PHP. This is also a MySQL Insert as well. I imagine you may want to do something with the data you have just received in PHP.

First, the form data i have serialized.

Serialized array of key value pairs from html form.

var data = [
{
"name":"CLIENT_ID",
"value":"111"
},
{
"name":"PROJECT_ID",
"value":"222"
},
{
"name":"USER_ID",
"value":"465605"
},
{
"name":"UTL_LATITUDE",
"value":"40.6110589"
},
{
"name":"UTL_LONGITUDE",
"value":"-111.8999353"
},
{
"name":"UTL_EVENT",
"value":"CLOCK IN"
},
{
"name":"UTL_ACTION",
"value":"MEETING"
}
];

Stringify it to submit to PHP...

The php_decode function is expecting JSON in this format.

[{"name":"CLIENT_ID","value":"111"},{"name":"PROJECT_ID","value":"222"},{"name":"USER_ID","value":"465605"},{"name":"UTL_LATITUDE","value":"40.6110589"},{"name":"UTL_LONGITUDE","value":"-111.8999353"},{"name":"UTL_EVENT","value":"CLOCK IN"},{"name":"UTL_ACTION","value":"TRAVEL"}]

.

<?php
/* Status Codes

return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */

/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);

// First get raw POST input
$raw_post     = file_get_contents('php://input');
// Run through url_decode..
$url_decoded  = urldecode($raw_post);
// Run through json_decode...
$json_decoded = json_decode($url_decoded, false); // false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.

$client_id      = (strlen($json_decoded[0]->value) > 0 ? $json_decoded[0]->value : null);
$project_id     = (strlen($json_decoded[1]->value) > 0 ? $json_decoded[1]->value : null);
$user_id        = (strlen($json_decoded[2]->value) > 0 ? $json_decoded[2]->value : null);
$utl_latitude   = (strlen($json_decoded[3]->value) > 0 ? $json_decoded[3]->value : null);
$utl_longitude  = (strlen($json_decoded[4]->value) > 0 ? $json_decoded[4]->value : null);
$utl_event      = (strlen($json_decoded[5]->value) > 0 ? $json_decoded[5]->value : null);
$utl_action     = (strlen($json_decoded[6]->value) > 0 ? $json_decoded[6]->value : null);

// INCLUDE DB CONNECTION STRING
//include 'php_pdo_mysql_connect.php';

mysqli_report(MYSQLI_REPORT_STRICT);

$host = 'localhost';
$db   = 'alpha1';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES   => false,
];

try {

$link = new PDO( $dsn, $user, $pass, $opt ); 

return $link;

} catch( PDOException $e) {

// Any error at this point...
$originalError = $e->getCode();

// MySQL Database connection refused..
if ($originalError == '2002') {

// Custom error.
echo '2';
exit;

}

}

// SQL INSERT query...
$stmt = $link->prepare("

INSERT INTO tbl_user_time_log 

( 
    CLIENT_ID, 
    PROJECT_ID,
    USER_ID,
    UTL_LATITUDE,
    UTL_LONGITUDE,
    UTL_EVENT,
    UTL_ACTION
)

VALUES 

( 

:client_id,
:project_id,
:user_id,
:utl_latitude,
:utl_longitude,
:utl_event,
:utl_action

) 

");

// Bind the corresponding parameter.
$stmt->bindParam(':client_id', $client_id, PDO::PARAM_INT);         // INT
$stmt->bindParam(':project_id', $project_id, PDO::PARAM_INT);       // INT
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);             // STR

$stmt->bindParam(':utl_latitude', $utl_latitude, PDO::PARAM_STR);   // STR
$stmt->bindParam(':utl_longitude', $utl_longitude, PDO::PARAM_STR); // STR



$stmt->bindParam(':utl_event', $utl_event, PDO::PARAM_STR);         // STR
$stmt->bindParam(':utl_action', $utl_action, PDO::PARAM_STR);       // STR

// Execute this SQL statement.
$stmt->execute(); 

// Catch pk generated for this new record. 
// $pk_user_time_log_id = $link->lastInsertId();

$link = null;
$stmt = null;

// return 1 = Successful Insert Query
echo '1';

?>
suchislife
  • 4,251
  • 10
  • 47
  • 78
  • I have the same code at the beginning, but the code stop at json_decode(i think) – maximran Jan 23 '18 at 04:36
  • Check out the updated answer with the array format. key value pairs. – suchislife Jan 23 '18 at 04:44
  • Inside the js script, i have stringify it, as i have inside my question. The json_decode will work, if i use the same string that i receive from POST but without using the `file_get_contents('php://input');` But when i directly use the input from file_get_contents, it fail – maximran Jan 23 '18 at 05:08
0

Actually the main problem is html characters and you can just use html_entity_decode() function which will convert all entities to their applicable characters!

json_decode(html_entity_decode('your variable here'));