JSON containing single quote causes syntaxerror - javascript

So I have data that needs to be fetched through php. This data should then be saved to a javascript variable in the .php file echoing the value:
$json = json_encode($requirements);
echo "<script>
var myvar = '<?php echo $json; ?>';
</script>";
The data contains a single quote which gives syntax error in Chrome:
Uncaught SyntaxError: Unexpected identifier
The page source look something like by the error:
var myvar = '<?php echo {"data":{"data":{"1":{"description":"Don' t}}}}; ?>';
where the entire string up until ""Don'" is in red.
What is the right way of keeping json_encode from failing (apart from calling the data directly to js)?

You need to escape ' chars then, for example by using backslash \:
{"data":{"data":{"1":{"description":"Don\'t}}}}
Or as you are using php you can use addslashes function

I have also experienced same problem with Single & Double quote.
You can resolve it easily by changing the single & double quote. Check below example.
$array = array(
"data" => array("data" => array ("desc" => "don't"))
);
$json = json_encode($array);
echo "<script>
var myvar = ".$json.";
console.log(myvar);
</script>";

You need to escape double quotes, Try:
var myvar = "<?php echo '{\"data\":{\"data\":{\"1\":{\"description\":\"Don\'t}}}}'; ?>";
alert(myvar)

Related

Is it possible to write javascript in php heredoc syntax?

I'm trying to output Javascript code heredoc syntax and I want it to be printed out with the PHP print_r function. Is it possible to do that?
PHP:
<?php
function printR($val){
echo "<pre>";
print_r($val);
echo "</pre>";
}
$str = <<<EOT
var msg = "Hello my name is ";
var name = "Jermaine Forbes";
function writeIt(m,n){
console.log(m+n);
}
writeIt(msg,name);
EOT;
printR($str);
?>
(by #FirstOne: I kept EOT; idented since there was* a comment about it)
Yes you can. If you expect to have only Javascript in the string (no PHP variable), I would use nowdoc instead of heredoc (use single quotes around the opening EOT
$str = <<<'EOT'
var msg = "Hello my name is ";
var name = "Jermaine Forbes";
function writeIt(m,n){
console.log(m+n);
}
writeIt(msg,name);
EOT;
Note also that the closing delimiter must be alone on the final line. You can't have any space before or after it. Your code didn't work because you have indented EOT;. From the docs:
Warning: It is very important to note that the line with the closing
identifier must contain no other characters, except a semicolon (;).
That means especially that the identifier may not be indented, and
there may not be any spaces or tabs before or after the semicolon.

Remove Backslash Escaping in Javascript Array

I have a pretty complex problem.
I'm using PHP to parse a CSV file to an array and then
var array = <?php echo json_encode( $array ) ?>;
to pass it to the Javascript array.
array is 2-dimensional, like so:
var array = [["\/\\ssa","14104","26","2113","0","867","28083","15","43695"],
["Yee","8661","24","2215","0","991","25245","15","49086"],...]
Now sometimes there seems to be a problem with backslash escapes in the username when it is structured like this:
["username\","sth","sth",...], so when the username ends with a backslash \ .
The output will be:
username", sth, sth, ...
But this is only the first element of the sub-array, the other 8 places are empty.
I have already tried to fix it with a loop replace, but I don't know how to add \" as search value. Is this impossible to do in JS since \" always escapes? Already tried charAt() to compare the last character with the backslash, but no success. Do I have to replace it before passing it to JS, in PHP?
The Parse function is this, if it's important:
<?php>
$url = "data.csv";
$csvData = file_get_contents($url);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
?>
Here a JSfiddle you can play with: https://jsfiddle.net/cLmbe0qf/
You just need to replace backslashes by an html special character :
foreach ($lines as $line) {
$line = str_replace("\\", "\", $line);
// ...
}
This is a little bit more tricky since you have to parse the javascript into an object/array. Anytime you do this, the backslash is parsed out. To avoid doing this you need to store the value in the HTML page or use String.raw to get the literal version of the string.
One way to implement it is to put the the string in the html and get the value of a hidden textarea. (you could store it anywhere, i just chose textarea). You then pass it through this javascript function slashParse which will replace all slashes with ~{}~ then run the javascript parsing algorithm, then replace the ~{}~ back to the backslashes.
function slashParse(target) {
var value = document.getElementById(target).value;
var replacedVal = value.replace(/\\/g, '~{}~');
var parsedVal = JSON.parse(replacedVal);
var mappedVal = parsedVal.map(function(item) {
return item.replace(/~{}~/g, '\\');
});
return mappedVal;
}
var parsed = slashParse('input');
console.log(parsed)
document.getElementById("test").innerText = parsed;
<body>
<div id="test"></div>
</body>
<textarea style="display:none" id="input">["use\rna</textarea><textarea>me\\","2","3","4"]</textarea>
What echoing it out onto the page might look like would be like this.
<textarea style="display:none" id="php-part">
<?=json_encode(htmlentities($array,ENT_NOQUOTES))?>
</textarea>
This is only one solution of a few more. Another option is to do more parsing on the php side of things. The problem you will run into, is that at some point you need to run the string through the JavaScript parsing program. When that happens you cannot have any backslashes. Then after you run it through the parsing, you will have to convert all hidden backslashes back to backslashes.
The one problem with this method is that if there is anywhere EVER where ~{}~ is being placed in the string, it will be converted to backslashes afterwards. Something you can do in order to make it more aloof is to make the string backslashes get turn into even more obfuscated. Such as ~{BACKSLASH_ESCAPE}~

call php var inside JS

Could you tell me why this is not working ?
<html>
<body>
<?php
$var1 = "hello";
echo $var1;
?>
<button type="button"
onclick="document.getElementById('demo').innerHTML = <?php echo(json_encode($var1)); ?>;">
HI</button>
<p id="demo"></p>
</body>
</html>
What should I do to be able to read the php variable from JS ?
Thanks
It is a string. The 's needed to added properly around the string.
onclick="document.getElementById('demo').innerHTML = '<?php echo(json_encode($var1)); ?>';"
As $var1 is string, you need to wrap that in quotes.
AS $var1 is string and not array or object, json_encode is not required.
Use quotes around the string(See the marked positions for quotes):
onclick="document.getElementById('demo').innerHTML = '<?php echo($var1) ?>'">
// ^ ^
Despite there are many answers, I will give my 2 cents about what I think the OP was thinking:
The basic idea was using json_encode to make the hello string to print "hello" instead of hello. The problem is actually that it will result in:
onclick="document.getElementById('demo').innerHTML = "hello";"
Which is NOT valid because of double quotes inside of double quotes.
Hence he can keep using json_encode if he wants to, as long as he changes the double quotes to single quotes:
onclick='document.getElementById("demo").innerHTML = <?php echo json_encode($var1); ?>;'
^ <-- single quote ^----^ <-- double quote here single there too --> ^
This should result in a valid output, which is:
onclick='document.getElementById('demo').innerHTML = "hello";'

PHP parses JavaScript content inside heredoc

<?php
$javascript = <<<EOT
<script type="text/javascript">
function test () {
return 'test test test \n test test test';
}
</script>
EOT;
echo $javascript;
?>
The \n above is parsed as newline by PHP, generates HTML source like the following
return 'test test test
test test test';
and this results in a JavaScript syntax error: unterminated string literal.
I have a big chunk of JavaScript code, so I don't want to wrap them like
$javascript = "<script type=\"text/javascript\">\nfunction test()...\n";
and actually the JavaScript code is not directly echo'd to the page, it is passed to another function, this is why I need a PHP variable.
So how can I define a PHP variable that contains a big chunk of JavaScript code whitout causing problems?
Is there a way like if / endif?
<?php if (condition): ?>
html code...
<?php endif ?>
Option 1: Use a NOWDOC, which is to HEREDOCs as ' single quotes are to " double quotes.
$javascript = <<<'EOT'
...\n...
EOT;
Option 2: Escape the special character:
$javascript = <<<EOT
...\\n...
EOT;
My code:
$javascript = <<<'EOT'
<script type="text/javascript">
$demo = 'test';
alert($demo);
</script>
EOT;
echo $javascript;
If i use 'EOT' then my code in javascript working well, but i use EOT then my code will understand $dem is variable in PHP

Assigning the content of a txt file on server to a javascript variable

Here is my problem (which is rather simple).
How can I assign the content of a file on my server to a javascript variable ?
Here is what I tried so far:
var count= <?php echo file_get_contents("compteur.txt");?>
But it doesn't funciton. BTW: I spent two hours on google already.
If content of the file is not not a numeric value then you have to use ' or " as below
var count= '<?php echo file_get_contents("compteur.txt");?>';
Simply outputting the file's contents in between single quotes will present a lot of pitfalls. If you're using PHP 5.2 or higher, you can use json_encode, which should be a lot more foolproof:
var count = <?php echo json_encode(file_get_contents("compteur.txt")); ?>
json_encode will take care of surrounding the value in quotes, so you do not need to put quotes before and after the PHP snippet.
On versions of PHP before 5.2, you can use this less robust technique for escaping the value:
function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
Source

Categories

Resources