I have an ajax function search for keywords in a big database. The php being called simply says “no” if there’s nothing, but if there are found records, it goes ahead and creates all of the HTML and returns the html, so that AJAX only needs to put the returned text into the html of a div. My problem is that I’d like to pass along a couple of variables, like the number of records found, etc.
So if I tried to put it in a statement that javascript could eval, I’m afraid that not only is all of the html potentially big enough to cause some sort of variable problems, but it also has a lot of single and double quotes, etc, that could unexpectedly end the variable before it’s supposed to. See the following
// (I know I don't have a single quote after data and that will break it. This is just an example
echo "{ status: 'success', total: '".count($relevance)."' data: ";
foreach ($relevance as $re) {
// tons of html is printed here
}
echo " }";
So the question is, how do I most effectively send back a whole gang of html code, along with some variables that can be easily eval’ed by JS?
Use
json_encodeThis will eliminate any errors you might have in trying to create your own json.