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>";
Related
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)
I have php array as bellow
$php_arr = json_encode(array('1'=>'"data1', '1'=>'data2'));
that json object i try to access inside Extjs as bellow
var test = Ext.JSON.decode()(<?php echo $php_arr; ?>);
but that gave to me error as
Uncaught Ext.JSON.decode(): You're trying to decode an invalid JSON String:
because of JSON object break "data1
How can I get this JSON object decoded in ExtJs without lose "?
Try this
var test = Ext.JSON.decode(<?php echo $php_arr; ?>);
and you must escape " like so
$php_arr = json_encode(array('1'=>'\"data1', '2'=>'data2'));
Also in PHP you can use addslashes, like so
$php_arr = json_encode(array('1'=>'"data1', '2'=>'data2'));
$php_arr = addslashes($php_arr);
Consider the code below to send a json string to js from php,
<?php
$str = "<!--<script>"; // This is from user input
?>
<script>
var json_str = <?= json_encode($str) ?>;
</script>
The string will break the HTML, and the way to solve it is via something like the old school comment hack, e.g.
<script>
<!--
var json_str = <?= json_encode($str) ?>;
//-->
</script>
Are there any alternative?
You can use the flag JSON_HEX_TAG, so that < and > will be encoded as \u003C and \u003E respectively.
json_encode($str, JSON_HEX_TAG)
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’ ;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"
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.