I feel like this must surely be a duplicate of an oft-answered question, but I cannot find an answer that addresses my particular issue.
I am loading data from MySQL via PHP, including some strings and a JSON-encoded string. This data may contain special characters, entered by the user.
I then combine this data into a PHP array, then json_encode
it and read it into javascript using JSON.parse
.
My issue is that an apostrophe in any of these strings will interrupt the javascript, preventing the JSON.parse
from completing.
I think there are three ways to solve this:
- Do some sort of encoding on the user-entered data before it gets saved to the database
- Escape the special characters when loading from the MySQL (using
htmlspecialchars()
or similar), though this will be difficult when loading data that's stored as a JSON string (I suppose I could decode it, then loop through and escape special characters in each element, then re-encode it). - Escape the special characters in javascript, somehow. But I don't know how I'd do this.
I would have to say that special character encoding is probably the single-most frustrating aspect of web development, as it causes me so many unexpected errors and I struggle to understand the different functions and when they should be used.
EDIT:
var feedback = JSON.parse('{"721103":[{"sessionid":"45","feedback":{"praise":["","",""],"development":["","",""]}},{"sessionid":"46","feedback":{"praise":["Test","Test's",""],"development":["","",""]}}') ;
The apostrophe in Test's
breaks the javascript