I’m building a CMS for a client (Building on top of wordpress). I’m having an issue with some data I am returning from my database.
Basically I am building Javascript Objects from PHP data so that I can update certain areas of my site upon mouse click.
example (this would work fine):
<script language = "Javascript>
var myObject = new Object();
function updateDiv(id)
{
myObject.name = '<?php echo $valueName ?>'; // $varHeadline = "Bob"
myObject.headline = '<?php echo $value_headline ?>'; // $varHeadline = "My Story"
var div = document.getElementById(id).innerHTML = myObject.name +
'<br>' + myObject.headline';
}
</script>
The problem comes up when the data I bring back from my database already has some html, or line breaks in it.
Example:
echo $varHeadline;
// returns <h1>This is my headline</h1>
// This is part of the value too.
So if I create a Javascript Object with that data:
function updateDiv(id)
{
myObject.headline = '<?php echo $varHeadline; ?>';
var div = document.getElementById(id).innerHTML = myObject.headline;
}
I get errors in my Javascript.
I would like to continue populating my divs with Javascript Object data, but am unable to on account of some of the data containing HTML (or even single or double quotes for that matter).
I DO want to retain my HTML formatting (the <h1> tags and so forth) so using htmlspecialchars or strip_tags is out of the question. Is there any die hard way of storing returned HTML without killing Javascript?
Thanks in advance.
-J
json_encode() the string and take away the quotes:
Of course, you could rewrite this as:
edit: as noted in the comments below, always make sure you can trust the HTML you’re placing on the page. If $valueName or $value_headline is coming from user input, this is a bad idea if you don’t validate the HTML in some other fashion, you’re open to XSS attacks and the like: http://en.wikipedia.org/wiki/Cross-site_scripting