1

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.

2
  • 4
    post an actual example of difficult input and desired output. You'll get better help that way. Commented 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. Commented Mar 14, 2011 at 13:05

3 Answers 3

5

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.

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

2 Comments

This looks much more like it.
@Kenyana: I don't know how your code looks like but if you have more than one row or more than one column then you can put your entire array in place of your_PHP_variable and have the array accessible in JavaScript.
3

You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.

3 Comments

Thanks, I was running htmlspecialchars instead of addslashes.
addslashes() is not meant for this. I'd rather use json_encode() instead, as rsp suggested.
@DaveVogt: Yes, it is. In the general case I'd agree with a JSON approach, but I think that's overkill for a string.
1

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

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.