JSON from localstorage not able to decode in php - javascript

I am fetching values from localstorage as JSON and trying to decode.
But its not working.
This my code to fetch JSON from localstorage:
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
When i echoed above $items it resulted like this:
{"items":[{"name":"Guitar","id":"1"}]}
Decoding above json like this:
$decoded = json_decode($items, true);
When i am trying to echo $decoded not displaying anything. When i did var_dump($decoded) its showing NULL
Any help is appreciated. Thank you.

The situation is that you're not able to combine JS/PHP "in one line".
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
json_decode from $items will give you directly the code that you've put in (check json_last_error())... without any JS execution (or you have to use PhantomJS; but it's not your case).
How it has to be:
JS part (sample.js):
jQuery.post('sample.php', {
'item': JSON.stringify(localStorage.getItem('itemList'))
});
PHP part (sample.php)
$items = filter_input(INPUT_POST, 'item');
$decoded = json_decode($items, true);
var_dump($decoded);

localStorage only stores strings. The JSON.stringify() is wrong since it expects a JSON object, not a string, as input.

Related

JS/PHP: Fetch does not send POST parameter [duplicate]

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
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 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)

After sending a Javascript POST request, how to retreive the data in php? [duplicate]

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
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 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)

covert a php array to json object , then back to array in javascript [duplicate]

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

Undefined Index in php: transfering variables from Ajax to php

Hello I tried to transfer variable from ajax to php, but php file keeps throwing me the following:
Undefined index: vals in /Applications/XAMPP/xamppfiles/htdocs/fang_sophie/project/sign in-out/bin/readall2.php
Ajax reads like this:
<script>
var var_data = "Hello World";
$.ajax({ url: 'bin/readall2.php',
data: {'vals' : var_data},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
</script>
Php reads like this:
<?php
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
?>
Why doesn't it work? Please help :)
One problem here is that you're trying to output JSON dataType:'json', where you don't have JSON to start with. Consult my footnotes also.
You need to use a text data type.
dataType:'text',
By the way, this won't echo anything at all (in the alert), since $hello is empty:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
You (may) want to echo the session array taken from the POST array, which is the logical thing to do:
echo($_SESSION['hello']);
Reference:
http://api.jquery.com/jquery.ajax/
Foonotes:
If by any chance you may be trying to access that (PHP) file directly, or your entire code is in the same file, then you need to use a conditional statement for it.
I.e.:
session_start();
if(!empty($_POST['vals'])){
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($_SESSION['hello']);
}
That, and/or use two separate files.
In regards to JSON; if you really want/need to use it, then set it back to dataType:'json', but use json_encode() for it and replacing echo($_SESSION['hello']); with and assigning the $hello variable to the session array:
$hello = $_SESSION['hello'];
echo(json_encode($hello));
<?php
//first start session
session_start();
//set header to json and UTF-8 encoding
header('Content-Type: application/json;charset=utf-8');
//check if $_POST['vals'] is set first using isset() to prevent notice
//undefined index
if(isset($_POST['vals'])){
echo "value of vals is: ".$_POST['vals'];
}else{
echo "vals not set";
}
?>
In your ajax request, the format of return is expect to be JSON. and you are returning a string.
You just need to add json_encode in your return line of php:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo(json_encode($hello));
The correct answer is you are reading the wrong variable:
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
It should be:
echo $_SESSION['hello'];
If you want the session data. For the undefined index, var_dump out your $_POST variable: var_dump($_POST);
If the $_POST variables do not match, or you get back an empty array, it was never transmitted to the server.
Original wrong answer:
When JQuery has "processData" flag set to false, it doesn't encode the data and requires the user reads it from the php://input stream.
Unencoded JSON is not sent into POST requests. For the quickest fix, try this:
parse_str(file_get_contents("php://input"), $vars);
// This will fill $vars with any data sent over to PHP.
var_dump($vars);
$vars should now be populated with the data you want. If $vars is empty, you are not transmitting the data.

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

Categories

Resources