2

I am using an XMLHttpRequest to POST a JSON string to PHP. The JSON object is created in JavaScript and using the JSON2.js from json.org to create an JSON string representing the object.

JSON.stringify(object);

Whenever the object contains a string which has a special character in it, e.g. é, JavaScript does not give any error but PHP receives an empty array

[]

Is there a JavaScript function which produces the exact same resutls as the PHP function

htmlentities()

The data is send via POST, so the following functions

escape()
encodeURI()
encodeURIComponent()

are a bit overkill.

Thanks!

4
  • a library like JQuery will perform this encoding for you Commented Mar 17, 2010 at 13:48
  • 2
    @Andy: jQuery doesn't do anything that isn't already natively available - it uses encodeURIComponent(). Commented Mar 17, 2010 at 14:08
  • @Andy E of course not, but why reinvent the wheel when AJAX libs abound? Commented Mar 18, 2010 at 10:02
  • If you're creating JSON you don't want to use an equivalant to htmlentities() as that will encode the results for injection in to HTML, not Javascript Commented Aug 11, 2011 at 15:04

1 Answer 1

6

Even when sending stuff via POST, you still need to correctly urlencode. If the ampersand character is in the JSON body, this would be treated as a parameter/value pair separator and your JSON would no longer be valid.

escape() is deprecated so use encodeURIComponent(). It shouldn't be overkill as this is one of the intended purposes of the function.

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.