json_encode escape special characters - javascript

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>

Related

PHP - return confirm within PHP issue

could somebody please help me with the below:
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
I know there is an issue with some " ' " but can't figure this out. I am getting a syntax error just before the 'Are'. The line of code was working as expected before I added the:
onclick="return confirm('Are you sure you want to claim this ticket?');"
Thanks!
If you want to use the same quotes you opened the string with inside the string itself, you should escape it.
For instance:
$var = 'Hello, let's go!';
echo $var;
This code will throw a parse error because this is how PHP sees the code:
) New variable $var.
) Is a string, declared using single quotes '.
) After the opening quote we have 'Hello, let'
) Now PHP expects some kind of valid code operators, like ., and next string or ;, but it gets some characters, which are treated as instructions rather than strings because they are outside the quotes, and
) PHP throws a parse error.
To fix this, you can use the backslash \ a.k.a 'escaping' character.
For example, to fix your problem:
echo
('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
See the baskslashes \ surrounding the single quotes inside the confirm JavaScript function? This tells PHP to treat these quotes as normal characters instead of string start/end declarations. Same thing works for reversal when you use double quotes as string declarators.
For example, when you want to show the actual representation of $ or any characters that have special meaning in a double quoted string, which allows direct insertion of variables (and some other's, like class properties) values you would use the escaping character.
For example:
$apples = 12;
$talk = "I have $apples \$apples. Thanks, now have a backlash! \\!";
echo $talk;
This will output I have 12 $apples. Thanks, now have a backslash! \!
Now, you are not actually required to escape the escaping character (it will show just as well if it does't have anything to escape after it).
Read this: PHP Manual - About Strings
You can also switch your single quotes on the edges of your echo statement with regular quotes, which will allow you to insert the $id variable easier. Then, you just have to escape the quotes around your JavaScript in onClick and switch all the other quotes to single quotes.
echo "<a href='assign.php?id=$id' onclick=\"return confirm('Are you sure you want to claim this ticket?');\" style='text-decoration: none'><font color='FFFFFF'><b>Click here to claim ticket</b></font></a>";
However, there is a better way.
Interpolate PHP into HTML
(Instead of HTML into PHP)
The best way to do this is to write HTML as HTML, and interpolate PHP variables into the HTML. This is best practice as it allows syntax highlighting in IDE's, and looks much cleaner/easier to read.
Just write the entire element as HTML, and then echo the $id variable inside the HTML (instead of writing all of the HTML in a PHP echo statement).
<a href="assign.php?id=<?=$id;?>" onclick="return confirm('Are you sure you want to claim this ticket?');" style="text-decoration: none">
<font color="FFFFFF">
<b>
Click here to claim ticket
</b>
</font>
</a>
With this method, you don't have to worry about escaping quotes, and it will allow you to use regular quotes throughout your entire element.
You need to escape the nested ' by doing \'
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
Note that all the stuff inside the single quotes is considered as string by the PHP interpreter.
Docs: PHP: Variables - Manual

JSON.parse ends up in 'missing ) after argument list'

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); ?>;

How to get single quotes inside a javascript variable (=function parameter) escaped? [duplicate]

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

json_encode() gives special charactors like '\n'..how can i replace them in PHP?

I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));

escaping single quotes for ajax calls

I have a php page which is called via AJAX. and basically it fetches some value from my database and echos back at table with inputs etc. The problem is when the string it fetches contains quotation marks(actually only single quotes seem to be effected). So on the php page there's something like this:
$value = htmlentities($DB_result->cloumn);
echo'<input type = "button" onClick = "$(\'#something\').val(\''.$value.'\');" />'
so if $value = "hello", no problems but if: $value = 'hello', the page which I'm making the AJAX call from throws up some such error: Syntax Error: unexpected identifier.
so I guess the quotations in $value have not been escaped, which I thought it would with the htmlentities. any Ideas how to solve this much appreciated. Thank you.
The problem is that $value contains single quotes, which interfere with the correct parsing of javascript. from the manual entry for html entities:
all characters which have HTML character entity equivalents are translated into these entities.
this means that your single quotes are not escaped, they are only translated in a way browsers will better understand. You need to use addslashes():
$value = htmlentities(addslashes($DB_result->cloumn));
"'hello'" will become "\'hello\'" which in the browser will look like:
<input type = "button" onClick = "$('#something').val('\'hello\'');" />
which will attribute the string 'hello' (with the single quotes) to the value attribute of $('#something')
Try:
$value = htmlentities($DB_result->cloumn, ENT_QUOTES, "utf-8");
Passing ENT_QUOTES through as a flag will convert both double and single quotes.

Categories

Resources