Invalid token when echoing PHP value in JS - javascript

I echo a PHP value into a JavaSript string, like this:
var x = '<?php echo addcslashes($_GET['value'], "'") ?>';
It works just fine, but when I set $_GET['value'] as "><script>alert('hi')</script> for example, I got:
Uncaught SyntaxError: Invalid or unexpected token
In DevTools, the string looks properly escaped, but is not, because it halts the rest of JS code.
var x = '"><script>alert(\'hi\')</script>';

The contiguous characters </script> cannot exist in an inline Javascript tag. The HTML markup is parsed before the Javascript, and </script> in the HTML markup after the start of a <script> tag indicates the end of that tag.
You can concatenate instead, so that, for example, your text would result in
var x = '"><script>alert(\'hi\')</scr' + 'ipt>';
by using str_replace:
$withSlashes = addcslashes($_GET['value'], "'");
$xContent = str_replace('</script>', "</scr' + 'ipt>", $withSlashes);
...
var x = '<?php echo $xContent ?>';
But it would be preferable not to dynamically construct Javascript code. Consider using data attributes instead, and to separate the Javascript into its own separate file, eg
<script
src="script.js"
data-x="<?php echo addcslashes($_GET['value'], "'") ?>"
></script>
(if you use this method, remember to properly escape "s if they can exist in the result)

Related

Use data-attribute in javascript to alter elements width

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:
Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):
<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>
The value of the data-attribute with the name "somedat" I want to use in js, like so:
var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;
What I did?
I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').
What is it that Im not getting? How can I solve my problem?
The proper way to pass data from PHP to JavaScript is using a JSON string.
PHP:
<?php
$arr = get_from_database_as_array(...);
// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";
HTML:
<script>
console.log(data);
document.getElementById("elem1").style.width = data["elem1"] + "px";
document.getElementById("elem2").style.width = data["elem2"] + "px";
// and so on.
</script>

how to save html to variable?

I try to save wysiwyg data to a variable but I keep getting a error message
"Uncaught SyntaxError: Unexpected token ILLEGAL"
And I cant get my head around it... I can se in the console that everything
is retrieved ok, anyone with an idea of what could be the error.
javascript
var temp = "<?php echo $pressDescription ?>"
console
You have to escape characters which have special meaning or are not allowed in JavaScript string literals (such as new lines).
The json_encode function will do that for you.
var temp = <?php echo json_encode($pressDescription); ?>;
Just use escape characters. For example:
var varName1 = '<p class="className">Sample text</p>';
var varName2 = '<p class=\'className\'>Sample text</p>';
var varName3 = "<p class=\"className\">Sample text</p>";

How To Escape a PHP Variable in Javascript?

I am trying to create a Javascript function that echoes out a Wordpress function called the_title() which just returns the title of the a blog. Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). Any help or explanation why this is happening?
THE CODE:
function createSliderTabs() {
var para = document.createElement("li");
var strings = "<?php the_title(); ?>";
var post_string = strings.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
var node = document.createTextNode(post_string);
para.appendChild(node);
var element = document.getElementById("control-navigation");
element.appendChild(para);
}
createSliderTabs();
THE RESULT:
Macy&#8217 ;s Herald Square (had to include space or it would've changed to single quote)
WHAT IT SHOULD BE:
Macy's Herald Square
Any help or guidance on why this is happening? Thx in advance...
From php to js transformation you always have to use json_encode().
to avoid xss
to describe unicode characters
You can use html_entity_decode:
I'm not really familiar with wordpress, but I suppose you would use it inside the_title():
function the_title()
{
$str = 'Macy’s Herald Square';
echo html_entity_decode ($str, ENT_COMPAT , "UTF-8");
}
If you need to use json_encode() you should be able to do
$json = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");
EDIT: added ENT_COMPAT , "UTF-8"

passing php string of JSON ( with qoutes) to onclick function

I'm trying to pass an array of data from php to java script for "onclick" event.
I do it by converting the array data into JSON string in order to parse it back in the js function and work on it.
The problem is that JSON string contains double quotes , so it arises an error as the double quotes break the html string (Uncaught SyntaxError: Unexpected token ILLEGAL ). I did see several questions similar to this, but didn't find a solution to what I need, or maybe I didn't understood the correct solution. So I bring it up here with my specific case.
<?php
..some php code here..
$aData = array("You","Me",76,array(3,6));
$sJSONstr = json_encode($aData);
?>
<input type="button" name="formSubmit" value="Delete" onclick="analyze('<?php echo $sJSONstr; ?>')">
<?php
..some php code here..
?>
and the js function is as follows:
function analyze(i_sInputDataJSONStr)
{
var aInputData = JSON.parse(i_sInputDataJSONStr);
.. So something with the input data array..
}
Use single quotes for the onclick attributes instead of double quotes. Single quotes is equally valid as double quotes.
One more thing, since you already have your data in JSON format, there is no need to put it as a string in the analyze function call, since your JSON data is a valid JavaScript array (that's what JSON stands for: JavaScript Object Notation).
Therefore, you don't have to parse the input string in your analyze function declaration.
Consider the following example, this is perfectly valid code.
<?php
$arr = ["Hello", "World"];
$json = json_encode($arr); // $json = '["Hello","World"]'
?>
<div id="myDiv" onclick='doSomething(<?php echo $json; ?>)'>Click me</div>
<script type="text/javascript">
function doSomething(data){
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
}
</script>
create a javascript string and pass it:
<script type="text/javascript">
var myjson = '<?php echo $sJSONstr; ?>';
</script>
and then:
onclick="analyze(myjson)"
<input type="button" name="formSubmit" value="Delete" onclick='analyze(<?php echo $sJSONstr?>)'>
Replace the double quotes with single quotes in onclick='';
Worked like a charm for me.

JSF facelet page doesn't javascript string with '&' character

in a JSF facelet page (.xhtml) I have this javascript code
<script type="text/javascript">
function navigateToDetail() {
var id = document.getElementById("idElemento").value;
alert(id);
var isPratica = document.getElementById("isPratica").value;
alert(isPratica);
var box = "#{boxCtrl.idBox}";
alert(box);
if (isPratica==true)
window.location = "DettaglioRichiesta.xhtml?id=" + id + "&box=" + box;
else
window.location = "../Richieste/DettaglioRichiesta.xhtml?id=" + id + "&box=" + box;
}
</script>
It doesn't work because the jfs engine think that "&box" is relative to a bindign, and it says:
Error Parsing /Box/ListaRichieste.xhtml: Error Traced[line: 20] The reference to entity "box" must end with the ';' delimiter
I can I avoid this behaviour?
Facelets is a XML based view technology. The & is a XML special character. It's interpreted as start of a XML entity like ,  , etc. It is therefore looking for the end character ;, but it found none, so it is throwing this error.
To represent the & literally inside a XML document, you need to use & instead of &.
window.location = "DettaglioRichiesta.xhtml?id=" + id + "&box=" + box;
You can also just put that JS code in its own .js file which you include by <script src> so that you don't need to fiddle with XML special characters in the JS code.
<script type="text/javascript" src="your.js"></script>

Categories