My question
My question is about correctly parsing HTML from php into a variable inside of a javascript object (which in this case is ace-editor's value variable)
My problem
I have got a textarea for HTML and CSS, the HTML gets retrieved from the database and needs to be inserted into a field of croppie, i am currently using PHP's json_encode functionality to put it inside of the variable, but it seems to still escape from the value.
My code
<?php
$css = ($modify) ? trim($template->style()) : "";
$html = ($modify) ? trim( $template->html() ) : "";
$html = json_encode($html);
$css = json_encode($css);
?>
YUI().use(
'aui-ace-editor',
function(Y) {
var editorhtml = new Y.AceEditor({
boundingBox: '#editor-html',
height: '400',
mode: 'html',
value: '<?php echo substr( $html, 1, -1 ); ?>',
width: '100%',
showPrintMargin: false
}).render();
var editorcss = new Y.AceEditor({
boundingBox: '#editor-css',
height: '400',
mode: 'css',
value: '<?php echo substr( $css, 1, -1 ); ?>',
width: '100%',
showPrintMargin: false
}).render();
}
);
What happens
When i use this, and open up a specific template which can be managed, i will not be able to see the textarea's (because the ace editor could not be loaded), i get random errors relating to line 666 which is the exact line the HTML gets stored in. I did sanitize the outputs in json_encode correctly.. right?
in this screenshot, you can see the HTML/css which gets inserted. But the problem occurs on line 666 which the HTML is located at. Click here if the screenshot isn't readable for you
So my question is..
Why exactly does it not parse the HTML into the object correctly? Am i not sanitizing it correctly or am i missing something?
You are breaking the output of json_encode by changing double quotes it creates to single quotes.
It's better to call json_encode directly when adding value to the script tag:
value: <?php echo json_encode($html); ?>,
Your issue is because your $html string contains single quotes, try escaping them or using double quotes
Related
I'm trying to put a php variable within a js script that is in a result variable that will be processed with json but i don't get it to work. I know it has something to do with the "" and '' but i can't figure out what it is.
$result["html"] .= "<script type='text/javascript'>setTimeout(function () { window.location='.$config[\"BURL\"].'; }, 2500);</script>";
Edit: whoohoo i got the 15 points to upvote! Thanks u all!
You will have to concatenate strings using . and remove the escaping of the quotes for the index, like so:
$result["html"] .= "<script type='text/javascript'>setTimeout(function () { window.location='" . $config["BURL"] . "'; }, 2500);</script>";
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.
I have this array:
$men['display']=array(
"edit" =>"1",
"description" =>"2",
"phone" =>"3",
"mail" =>"4"
);
I tried to transfer it to javascript by using:
<?php $disArray = json_encode($men['display']);?>
then, I sent it to javascript:
<select id="selectBoxHere" onChange="loadInnerHTML('<?php $disArray ?>')";>
For some reason, my javascript function 'loadInnerHTML' dosen't send my array to javascript.
You forget the echo statment.
And if you use single quotes, it makes this a string. For a javascript object you don't need the single quotes, json_encode will ensure it is javascript safe.
loadInnerHTML(<?php echo $disArray ?>)
I'd also recommend that you store this variable directly in javascript first, rather than passing it into a function. Otherwise you have to worry about double quotes inside double quotes, breaking your <select> tag.
var disArray = <?php echo $disArray ?>;
Then you can just use that variable.
loadInnerHTML(disArray)
Echoing an array in php will result in
var dis_array = Array
which js couldn't understand. Try:
var disArray = JSON.parse( '<?php echo json_encode( $disArray ) ?>' );
I want to pass $_GET value to window.open, but how?
My current code can't pass $_GET value:
function googlemap() {
ver id = <? php print ''.$_GET['buid'].''; ?>
window.open("Views/Admin/addresstomap.php?bid=+id", "myWindow",
"status = 0, height = 600, width = 800, resizable = 0 top=200, left=300,scrollbars=no,toolbar=no, location=no, directories=no, ")
}
You're not using the variable in the window.open call, you're just using a string with the name of the variable:
"Views/Admin/addresstomap.php?bid=+id"
JavaScript won't interpret id from that string. You need to separate it from the string itself:
"Views/Admin/addresstomap.php?bid=" + id
Additionally, you have a typo in the var keyword and you're missing a semi-colon. This:
ver id=<?php print''.$_GET['buid'].''; ?>
should be this:
var id=<?php print''.$_GET['buid'].''; ?>;
Indeed, you may even need quotes around it if the variable is supposed to be a string. (I don't know if it is, but you should be able to figure it out.) In that case the line would be:
var id="<?php print''.$_GET['buid'].''; ?>";
(Note: Given these errors, there may still be others that I haven't noticed. You'll want to do some debugging, check your PHP logs, check your JavaScript console, etc.)