2

I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.

Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.

3
  • could you post the code you've used to store HTML in JavaScript? Commented Jun 17, 2011 at 17:31
  • Sounds like it might be a HTML escaping issue. Could use more info/code though to clear this up. Commented Jun 17, 2011 at 17:31
  • Looks like the same question as stackoverflow.com/questions/3176744/… Commented Jun 17, 2011 at 17:52

2 Answers 2

2

Since you're using PHP:

<script>
    var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>

The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.

Sign up to request clarification or add additional context in comments.

2 Comments

To clarify, calling json_encode on a php string will output the correct code for a JS string, that is, wrap it with quotes and escape characters in the strings.
won't you need to wrap the result from json_encode with quotes on the outside? e.g. var foo = "<?php etc %>";
0

"Safefy" your code, like this

str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));

The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.

and inline it in javascript,

//<![CDATA[ 
    var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>

keep in mind the '"' part so that it appears like this var myHtml = "test";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.