Expanding on someone else's answer:
<script>
var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>;
</script>
Using json_encode() requires:
- PHP 5.2.0 or greater
$myVarValueencoded as UTF-8 (or US-ASCII, of course)
Since UTF-8 supports full Unicode, it should be safe to convert on the fly.
Please note that if you use this in html attributes like onclick, you need to pass the result of json_encode to htmlspecialchars(), like the following:
htmlspecialchars(json_encode($string), ENT_QUOTES);
or else you could get problems with, for example, &bar; in foo()&&bar; being interpreted as an HTML entity.
Expanding on someone else's answer:
<script>
var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>;
</script>
Using json_encode() requires:
- PHP 5.2.0 or greater
$myVarValueencoded as UTF-8 (or US-ASCII, of course)
Since UTF-8 supports full Unicode, it should be safe to convert on the fly.
Please note that if you use this in html attributes like onclick, you need to pass the result of json_encode to htmlspecialchars(), like the following:
htmlspecialchars(json_encode($string), ENT_QUOTES);
or else you could get problems with, for example, &bar; in foo()&&bar; being interpreted as an HTML entity.
encode it with JSON
You can use the wp_localize_script to pass a variable to your javascript.
Here is an example:
wp_register_script('your_script_name', 'path/to/script.js');
$variables = array (
'footer_caption' => $attr['footer_caption'],
);
wp_localize_script('your_script_name', 'js_object_name', $variables );
wp_enqueue_script('your_script_name');
Then you can acces to this variable by:
js_object_name.footer_caption
Can you post how you tried to use localize_script? Because i use the function often for passing PHP vars to JavaScript and it always worked.
Another way would be to echo the variable in shortcode_ui_chart so you later can use it in your script:
echo '<script type="text/javascript">var footer_caption = "' . $attr['footer_caption'] . '"</script>';
With this code you can use the variable footer_caption in your javascript.
EDIT: See comments for code explanation
var chart1 = Highcharts.chart({
chart: {
events: {
load: function () {
var caption 'footer_caption'
var label = this.renderer.label(caption)
}
}
}
});
You should just use json_encode() from http://www.php.net/manual/en/function.json-encode.php
Example:
var str1 = <?php echo json_encode($str) ?>;
It takes care of converting newlines to \n, escaping any other special characters as necessary, preserve spaces, etc.
Example output for your string:
var str1 = "\n this\n is\n my\n string";
Problem is EOL character in your PHP strng.
Use it like this (after replacing all EOL characters with a space):
var str1 = '<?php echo str_replace("\n", " ", $str) ?>';
Try this:
echo '<td><input id="btnUpdate" type="submit" name="btnUpdate" value = "Update" onclick="updateButton("' . $row['CustomerID'] . '","' . $row['custEmail'] . '")" /> </td>';
You need quotes around the string
echo '<td><input id="btnUpdate" type="submit" name="btnUpdate" value = "Update" onclick="updateButton(' . $row['CustomerID'] . ',\'' . $row['custEmail'] . '\')" /> </td>';
echo"
<table>
<p><input type='text' id='newPostComment' value='' placeholder='WRITE YOUR COMMENT HERE...' size='35'/><input type='submit' value='UPLOAD' onclick='uploadPostComment(\"$parentID\", \"" . str_replace('"', '\"', $comment) . "\");fetchComment()'/></p>
</table>
You need to quote the fields. If your field is an integer it does not need to be quoted, if it is a string it needs to be. I quoted both because I don't know if parentID is a string id or a numeric id. Do what your application needs of course.
Update: in regards to Michael's comment about breaking if comment contains a quote. We now escape all double quotes in $comment to prevent that.
<input type='submit' value='UPLOAD' onclick='uploadPostComment($parentID, $comment);fetchComment()'/>
is your culprit, especially uploadPostComment($parentID, $comment); - if $comment is a string, you need to put quotes in place: uploadPostComment($parentID, \"$comment\");
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
I'm really just re-wording what @Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that @Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
Change your Line 5 - Line 7 code to:
echo '<div class="FloorH">
First Floor <button onclick="changeBG(\'' . $floorDiv . '\',\'#F0F\');">Magenta</button>
</div>';
because PHP will not parse variable inside single quote quoted string .
More detail of variable parsing within double quotes string you can check out this php documentation variable parsing
PHP alternative syntax is much easier for HTML templating
<?php for ($floorNow = 1; $floorNow <= 5; $floorNow++) :
$floorDiv = 'floorData' . $floorNow;
?>
<div class="FloorH">
First Floor
<button value="<?= htmlspecialchars($floorDiv) ?>"
onclick="changeBG(this.value, '#F0F')">Magenta</button>
</div>
<div id="<?= $floorDiv ?>"></div>
<?php endfor ?>
$page =
"<script type=\"text/javascript\">
function outf(text) {
var mypre = document.getElementById(\"output\");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles[\"files\"][x] === undefined)
throw \"File not found: '\" + x + \"'\";
return Sk.builtinFiles[\"files\"][x];
}
function runit() {
var prog = document.getElementById(\"yourcode\").value;
var mypre = document.getElementById(\"output\");
mypre.innerHTML = '';
Sk.canvas = \"mycanvas\";
Sk.pre = \"output\";
Sk.configure({output:outf, read:builtinRead});
try {
eval(Sk.importMainWithBody(\"<stdin>\",false,prog));
}
catch(e) {
alert(e.toString())
}
}
</script>";
<?php
fwrite($fh, $page);
?>
use here doc like so:
$page = <<<EOF
<script type="text/javascript">
.....enter the rest of the code here...
</script>
EOF;
echo $page;
find a manual to learn how to use heredoc
The best way IMHO would be this:
tagName: <?php echo json_encode($tagged); ?>
This way, you don't have to take care of escaping quotes, escape characters or other unwanted signs.
If your view is rendered by PHP:
tagName: '<?= json_encode($tagged)?>',
If your JS code is a part of a PHP view, build the object from PHP:
$jsObject = json_encode(array('tagName' => $tagged'));