2

I was told that escaping HTML characters before entering them into a DB is a bad idea, so I have been modifying my code so that the raw input is stored without escaping. Now I am having a problem outputting the data onto a web page.

In PHP, I use htmlentities() for my output and it works fine, but I am using AJAX to retrieve my data, and thus have to output using JavaScript.

I have tried using the escape() function in JS but my output is not coming out properly. The sample text that I am using to test is:

One, two, & three

I know that it is the ampersand causing issues so my first question is - how do I escape this for output using JS? When I remove it, I get this:

One,%20,two,%20three

... so my second question is, what am I doing wrong here?

Any ideas? I'm sure this is simple for many of you.

3
  • 2
    Mmh why don't you use htmlentities() for the Ajax response as well (when the response is generated at the server side)? Commented Feb 26, 2011 at 22:28
  • Thats it ;-) The page, which is called by Ajax should output it with htmlentities() or htmlspecialchars(). If not possible why ever there are so much htmlspecialchars or htmlentities scripts with javascript, e.g: phpjs.org/functions/htmlspecialchars or phpjs.org/functions/htmlentities Commented Feb 26, 2011 at 22:34
  • thank you both for your reply. it seems like it takes another person or person(s) to make you realize the answer is so simple =]. Ahmet - thanks for that reference. I didn't know JS translations of PHP functions actually existed. Commented Feb 26, 2011 at 22:38

1 Answer 1

2

(as it seems to have helped you, I will put it as a proper answer)

You can still use htmlentities() if you use Ajax. Just use it for the response that is generated on the server, like you would if you returned HTML. There is no difference.

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

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.