How to encode json and special characters from php to javascript? - javascript

In my db I save the json in a custom field called usp-custom-12 like this:
[{"Mamma":["Papa"]}]
Then I try to decode that
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = <?php echo htmlspecialchars_decode($jsonTable); ?>;
But it is giving me
var data = "[{"Mamma":["Papa"]}]";
And a console log error:
Uncaught SyntaxError: Unexpected identifier
The full code:
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = "<?php echo htmlspecialchars_decode($jsonTable); ?>";
console.log(data);
data = JSON.parse (data);
data.forEach(obj => {
Object.keys(obj).forEach(key => {
$('#newTable thead tr').append($('<th>').text(key));
obj[key].forEach((e, i) => {
if(!$("#newTable tbody tr:eq("+i+")").length) $("<tr>").appendTo($("#newTable tbody"));
$("#newTable tbody tr:eq(" + i + ")").append($('<td>').text(e))
})
})
});
In this jsFiddle if you click save table you will see it generates a table identical to the top one, that's also logging in console the correct json: https://jsfiddle.net/fbh0o67o/74/

$jsonTable contains a JSON string with html entities encoded, since it's already JSON, you just have to decode the html etities and echo it as is. No JSON decoding is required, no quoting is required. Just HTML decode and echo it into your javascript.
var data = <?php echo htmlspecialchars_decode(usp_get_meta(false, 'usp-custom-12')); ?>;
data.forEach(obj => {
// Loop stuff here...
});

The issue is with the quotes inside the string "mama" you need to escape those quotes using addslashes method.
Try using the following:
var data = "<?php echo addslashes(htmlspecialchars_decode($jsonTable)); ?>";

JSON to PHP:
json_decode($string);
If you use the optional parameter $assoc as true - json_decode($string, true) will return associative array on success.
PHP to JSON:
json_encode($array);
PHP manuals:
json_encode()
json_decode()

Related

Validate JSON with json schema is failing

Hi I need to do a school assigement with a API thats generating json.
I get with $API my json. With some testing by myself I can say that the json is correct. But in the assigement it says I need to validate it with a json schema. I have the schema but I cant get it to work so it will check and validate the incomming json.
If someone sees the problem pls tell me because I cant find it.
<?php
//Json gets validated
if(isset($API))
{
?>
<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js">
var validator = require('validator');
var jsv = require('json-validator');
jsv.validate("<?php echo $API; ?>", "json_schema.json", function(err, messages)) {
if(err)
{
throw err;
}
else
{
$.getJSON("<?php echo $API; ?>", function(data)
{
var items = [];
$.each(data, function(key, val, val2) {
items.push("<li id='" + key + "'>" + val["COL 3"] + "</li>");
items.push("<br>");
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo(".datapanel");
});
}
}
</script>
<?php
}
?>
Replace both <?php echo $API; ?> by <?php echo str_replace('"', '\\"', $API); ?>.
Even better, you could have this process once and then echo the escaped string:
<?php
// Json gets validated
if (isset($API))
{
// escape your JSON string
$escapedAPI = str_replace('"', '\\"', $API);
?>
...
<!-- echo the escaped string -->
<?php echo $escapedAPI; ?>
...
<?php
}
?>
The issue you're facing is that currenty, when PHP echo the JSON in your Javascript, it produces something like this:
jsv.validate("[{"COL 3":"(APPLAUSE)"}, ... ]", "json_schema.json", function() { ... })
As you can see, the " from the Javascript are mixed with the one "echoed" which produce invalid Javascript. This is why you need to escape them before "echoing" your JSON.

$_POST returning Array () and echoes nothing if I try to index

I am trying to pass an object (I think its an object( its an associative array/dictionary with an indexed array for values)) to a PHP file so that I can insert data into a database. Every time I try to access the contents of the array in PHP it returns Array() or Array depending on what I try. I have tried to user $.ajax() as well but results in the same problem.
function postData()
{
data = JSON.stringify(dataObject);
alert(data);
$.post("submit_order.php",
data,
function(status){
alert(status)
window.location.href = "submit_order.php";
});
}
This is what the data structure looks like after using JSON.stringify()
{
"order":[
["2","chicken panini","3.95",1],
["1","cakes","3.55",1]
]
}
This is what I am trying to access the values and the data structure itself. As you can see I have tried all sorts.
<?php
print_r($_POST);
echo $order[0][0];
echo $_POST['order'][0][0][1];
print_r($_POST['order'][0]);
print_r($_POST['order'][0][1]);
print_r($_POST['order'][0][0][1]);
foreach ($_POST as $key => $value) {
echo $key;
}
When I print_r($_POST); it gives me
Array()
{"order":[["2","chicken panini","3.95",1],["1","cakes","3.55",1],["3","big_cake","2.55",1]]}
is sent with the POST request.
function postData()
{
data = JSON.stringify(dataObject);
$.post( "submit_order.php", function( data ) {
alert("success");
});
}
try this function instead.
You transfer you data as a JSON string - so you have to json_decode it on the PHP side.
<?php
print_r(json_decode($_POST['order']));
?>
In your code for the second argument you must send the parameters between {} as:
$.post( "submit_order.php", { data: data }, function(status){
alert(status)
window.location.href = "submit_order.php";
} );
<?php
if(!empty($_POST['order])){
$_POST['order] = json_decode($_POST['order]);
foreach($_POST['order'] as $order_key => $order_value){
echo $order_key ." =>". $order_value;
}
}
?>
Try this :)

How to read data from in Javascript

I'm trying to use Javascript to read stock data from yahoo finance at "http://table.finance.yahoo.com/table.csv?s=000001.sz", which returns a csv file and convert the data into json format as in http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=? to be used in highcharts.
I tried using $.ajax get and jquery.get but neither worked. Can somebody tell me how to read the data from the url and convert it into json? Thanks a lot.
This can be easily done with PHP.
<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));
//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$arr = csv_to_array('data.csv');
//<pre></pre> tags appear only to prevent white-space collapsing
//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";
//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>
Now depending on the format of JSON that it acceptable to Highcharts API, you are required to tweak how the array is encoded into JSON.
Also avoid using JSON_PRETTY_PRINT if the size of the incoming data is large.
I guess you are facing Cross Domain issue. Use jsonp calls for Cross Domain requests. Use something like this
$.ajax({
url : "http://xx.xx.xx.xx/xxx/xxx",
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {alert("Success");},
error: function(data) { alert("Error"); }
});
});

How to Pass Two Values From PHP to Ajax

Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});

how to pass json object into javascript function in php

i have a json object.
$json = json_decode($data,true);
it looks like-
array(5) {
["screenShareCode"]=>
string(9) "021113322"
["appletHtml"]=>
string(668) ""
["presenterParams"]=>
string(396) "aUsEN5gBYi4vlIEGpk0="
["viewerUrl"]=>
string(65) "http://api.leap.com/v2/viewer/021113322?accountid=mynet"
["origin"]=>
string(3) "API"
}
alert('?php echo $json; ?>');
when i am trying to assign this into javascript variable it gives me an error saying "unterminated string constant".
You don't decode it, in PHP or JavaScript. The contents of a JSON string is a valid JavaScript literal.
<?php
...
?>
<script ...>
var data=<?php echo $data; ?>;
alert(data["screenShareCode"]);
<?php
...
Try:
alert(<?php echo json_encode($json); ?>);
or:
alert(<?php echo $data; ?>);
You're a bit confused about terminology. $data is a JSON string, $json is a PHP array that you got by decoding the JSON string.
Try the following code. I have created a php file named sample.php. We have a php array named $data. Encode that data in to json using json_endode(). That results json formatted data. Then we can assign it into a java script variable like var jsonData = <?php echo $jsonData ?>; Note that this is done inside <script> tag.
<?php
// We have some data
$data = array(
"screenShareCode"=>"021113322",
"appletHtml"=>"",
"presenterParams"=>"aUsEN5gBYi4vlIEGpk0",
"viewerUrl"=>"http://api.screenleap.com/v2/viewer/021113322?accountid=mynet",
"origin"=>"API"
);
// Convert it into json format.
$jsonData = json_encode($data,true);
?>
<script>
// Assign that json data to a java-script variable
var jsonData = <?php echo $jsonData ?>;
// To view the full data
console.log(jsonData);
// You can take a specific data like this.
alert(jsonData.presenterParams);
</script>

Categories

Resources