I want to pass an php array to js. For this purpose I use json_encode an then in js JSON.parse().
Now the Problem ist, that JSON.parse trow an exception 'missing ) after argument list'. I guess it's apostrophes in numbers (number_format > CHF).
clippings:
<script>
(function($) {
var prices = JSON.parse('<?= $this->prices_json; ?>'); ...
... "offsetdruck_4f":{"1s":"583.82","2s":"1'090.09"}...
have single quotes to be escaped? If so, how best to do it?
is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
have single quotes to be escaped?
Single quotes inside a JavaScript string literal that is delimited with single quotes do have to be escaped.
… and that is what you have: 'data with ' and then at the end'.
If so, how best to do it?
To not use a JavaScript string literal at all.
JSON is a subset of JavaScript literal notation, so just treat it as JavaScript. Don't try wrapping it in a string and then explicitly parsing it.
var prices = <?= $this->prices_json; ?>;
try php: addslashes(json_encode($php array))
have single quotes to be escaped? If so, how best to do it?
json_encode should escape everything needs to be escaped.
is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
You should use json_encode in order to be sure that the output is correct. Do not rely on default array output. It has nothing to do with JSON.
You don't need to use JSON.parse here at all.
var prices = <?= json_encode($this->prices_json); ?>;
Related
I would like to pass a php array to a jQuery function.
I tried to send the array as json_encode like this:
<button onclick='callFunction(<? echo json_encode($myArray); ?>)'></button>
the result of my json_encode array is:
{"Date":"2018-01-26 12:55:00","Details":"FORLI IT"}
All works good.
But if I have an array like this (with a ')
{"Date":"2018-01-26 12:55:00","Details":"FORLI' IT"}
My function doesn't work anymore - my console will show:
SyntaxError: Unexpected EOF
How can I solve this problem?
The way I suggest you deal with anything that goes to html is:
<button onclick='callFunction(<? echo htmlentities(json_encode($myArray),ENT_QUOTES); ?>)'></button>
Check all available flags at http://php.net/manual/en/function.htmlentities.php
This one uses the flag ENT_QUOTES because the default behaviour is to only encode double quotes. Using ENT_QUOTES will also encode single quotes.
Try using addslashes,
<button onclick='callFunction(<? echo json_encode(addslashes($myArray)); ?>)'></button>
In PHP, I use json_encode() to echo arrays in HTML5 data attributes.
As JSON requires - and json_encode() generates - values encapsulated by double quotes. I therefor wrap my data attributes with single quotes, like:
<article data-tags='["html5","jquery","php","test's"]'>
As you can see, the last tag (test's) contains a single quote, and using json_encode() with no options leads to parsing problems.
So I use json_encode() with the JSON_HEX_APOS parameter, and parsing is fine, as my single quotes are encoded, but I wonder: is there a downside doing it like this?
You need to HTML escape data echoed into HTML:
printf('<article data-tags="%s">',
htmlspecialchars(json_encode(array('html5', ...)), ENT_QUOTES, 'UTF-8'));
or use the build-in option:
json_encode(array('html5', ...), JSON_HEX_APOS)
you can check it up in the manual: http://php.net/manual/en/json.constants.php#constant.json-hex-apos
I've used json_encode($array); to convert an array to a json.
[{"x":1418736600,"y":"82.2"},{"x":1418736900,"y":"82.2"}]
But what I really need is a JavaScript object like the following:
[{x:1418736600,y:"82.2"},{x:1418736900,y:"82.2"}]
To make it short I would like a JSON without quoting the keys, but it would be preferable avoiding parsing what json_encode outputs and using a more straightforward way instead.
Is it possible to do this in PHP?
Other than making the payload very slightly smaller, there's no need to do this. The output of json_encode is valid JavaScript code, if used where a value is expected, e.g.:
var x = <?php echo json_encode($array); ?>;
The quoted property keys are valid JavaScript. JSON as a whole is, in fact, a subset of JavaScript literal syntax.
You could throw a regular expression at the result. It can probably never be perfect (JSON, like HTML, can't be correctly parsed with a single regular expression), but within a limited domain you might be able to do it. For instance, here's a naive version that would probably work for many data sets, including your example, though again it would not work with all data sets by any means:
<?php
$str = json_encode($array);
$str = preg_replace('/"([A-Za-z0-9_$]+)":/', '$1:', $str);
?>
var x = <?php echo json_encode($array); ?>;
That assumes anything that consists of just A-Z, a-z, 0-9, _, or $ between double quotes followed immediately by a colon is a key and removes the quotes. (That's not a complete list of valid JavaScript identifier characters, it's just an example.)
But it seems unlikely to me that the savings are worth the bother.
To do it correctly, of course, you'd have to do your own serializer. It wouldn't be all that hard, just a recursive function that handles descending into arrays and objects. It could still use json_encode for the values.
I have JSON data passed by PHP and I need to parse it in Javascript.
item = JSON.parse('<?=json_encode($item_localized);?>');
Some trouble. I have string in $item_localized which contains single quote. Jsonlint says it valid json. Because I use '<?=json_encode($item_localized);?>' - I receive message Uncaught SyntaxError: Unexpected identifier. I cannot use double quotes. I tried replace single quotes with \' but it's not working.
json_encode will generate a JSON text.
JSON.parse needs to receive a string containing a JSON text.
You do need to quote the string, but you can't simply place ' around it because that won't escape any characters in the string that have special meaning in a string literal (like other ' characters).
If you put a string into json_encode then you will get out a JSON text consisting of a string representation of another JSON text. Since JSON is a JS subjet, that string will be JS safe:
item = JSON.parse(<?php echo json_encode(json_encode($item_localized)); ?>);
This is, however, silly. Since JSON is a subset of JavaScript, you can just use it directly as a JavaScript literal.
item = <?php echo json_encode($item_localized); ?>;
What about item = <?=json_encode($item_localized);?>;?
I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.