tags:

views:

203

answers:

4

Hi, I am pulling html from my database with a jquery ajax request.

However, if there is a single quote ('), I get a parsing error.

Regular quotes work fine (").

For example, in my database I have:

style=font-family:"times' new roman"

(I put the ' in there after times for testing). With the ' gone it works...

I start the request:

$.ajax({
       url: "phps/file.php?id="+id,
       dataType: "json",
       error: function(uno,dos,tres){

My php file does:

$code = mysql_real_escape_string($results['code']);
//return
header('Content-type: application/x-json');
echo '{';
echo '"code": "' . $code. '"';
echo '}';

The jquery error function gives me:

[object XMLHttpRequest]
parsererror
undefined

I think this is the issue, but I don't know how to fix it:

We are now strict about incoming JSON and throw an exception if we get malformed JSON. If you need to be able to evaluate malformed JSON that is valid JavaScript, you can make a text request and use eval() to evaluate the contents.

Thanks!

+6  A: 

I would change your PHP to:

header('Content-Type: application/json');
echo json_encode(array('code' => $code));

Namely, change the MIME type to application/json and use PHP's native json_encode() rather than manually constructing JSON.

cletus
+1 For also correcting JSON’s media type.
Gumbo
+2  A: 

I think the best thing to do would be to use json_encode:

header('Content-type: application/x-json');
echo json_encode($results);`

Or you could replace the " with \" in the string and it should be valid JSON from what I can see. str_replace("\"", "\\"", $code)

Or if neither of those options work, do the text request with jQuery. I'm not sure on the exact syntax though.

This JSON Validator may prove useful to you: http://jsonformatter.curiousconcept.com/

David Hogue
A: 

Thanks! I've almost got it. However, like munch said, I shouldn't use mysql_real_escape_string before outputting the data. I looked it up and it seems like I want either:

   a.) $code = htmlspecialchars($results['code']);
   b.) $code = htmlspecialchars($results['code'], ENT_QUOTES)
    or
   c.) $code = htmlentities($results['code']);

I think htmlspecialchars (a) is preferred, but please tell me if I am wrong.

I am setting the innerHTML of a div to the code with javascript.

If I use a,b, or c I get the actual text of the code inside the div. For example I would get:

<"img src="test.gif"/>" as plain text.

I get the actual image if I do:

$code =$results['code'];

I think I need to use a,b,or c for security though. Any ideas?

Thanks

jeord
A: 

Actually, I'm thinking I should use:

$code =$results['code'];

I'm pretty confused about the encoding and character sets. However, I just thought of something...

Maybe you usually use htmlspecialchars and htmlentities so users cannot input html or javascript...however I am trying to display the html.

jeord