Here’s my problem. I have data being returned using JSON, AJAX from my php script to my page. The data is being stored in a variable data
Using the variable data, I’m trying to construct a div using javascript. However, if the data contains a single quote, it break my js code and the page script doesn’t work.
example code with data being the variable containing data “The boy’s bicycle”:
var newrootcomment = $("<div id='container'>" + data + "</div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
How do I solve this problem?
Are you using the
json_encodefunction available in PHP? Are are you treating the response as JSON?jQuery.parseJSON(<json-string>).From there you interact with it simple as an object.
If you don’t have jQuery, most browsers support
JSON.parseJSON().Also, make sure you use double quotes for attributes.
This is normally how I use json_encode: