Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
-
4post an actual example of difficult input and desired output. You'll get better help that way.dnagirl– dnagirl2011-03-14 12:50:07 +00:00Commented Mar 14, 2011 at 12:50
-
Michael I had a class that was injecting the code into the head. Actually developing a custom joomla component that works with google maps. That's why I needed the js to be created dynamically.Churchill– Churchill2011-03-14 13:05:20 +00:00Commented Mar 14, 2011 at 13:05
3 Answers
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
3 Comments
addslashes() is not meant for this. I'd rather use json_encode() instead, as rsp suggested.You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php