tags:

views:

37

answers:

2

I have a dynamic string from PHP that I encoded using htmlentities() so I can pass it on AJAX using jQuery and JSON. Now I got something like

{ "error": "false", "html": "<div id="user_add_title">Adding New User<div class="showhide-div"><a class="hideShowToggle" href="#" onclick="$('#account_title').show();$('#account').show();$('#users_container').html('')">[cancel]</a></div></div>" }

and when I want to show it in an AJAX success callback function like:

success: function(json) {
    if(json.error == 'false')
        $("#users_container").html(json.html);
    else
        showMsg(json.msg);
}

what's displayed in the is the entities itself

<div id="user_add_title">Adding New User<div class="showhide-div"><a class="hideShowToggle" href="#" onclick="$('#account_title').show();$('#account').show();$('#users_container').html('')">[cancel]</a></div></div>

instead of being rendered by the browser.

If I use html or text as dataType in my jQuery AJAX call, the tags are rendered properly. I want to use JSON because I need to catch if the process has an error or not.

A: 

You don't need to encode your own markup with htmlentities when passing it to jQuery. Simply remove the call to htmlentites() and send your marked up HTML.

The exception is, if some part of the code contains text supplied from the user. In this case, you must htmlencode() that text, and leave it encoded even when it's appended to a DOM element for display.

meagar
A: 

I have solved it! Instead of using PHP's htmlentities() which converts greater than and less than signs as well as the quotes, I just used addslashes() to only convert (or add backslashes) characters that need backslashing such as the quotes.

I figured out that the quotes were the ones causing the json not being parsed correctly, the reason why I used htmlentities in the first place, thinking that converting everything would solve it. Thanks for your valuable input.

Harvey Diaz
You should be producing your JSON content with `json_encode`. Specifically for strings only, `addslashes` will do in a pinch, but it doesn't have the options JSON_HEX_TAGS or AMP or QUOT which you often need when the JSON is going to end up in a script block or inline event handler. Speaking of which, avoid passing inline event handler code in HTML back. You've got HTML in JavaScript in HTML in JavaScript... no wonder the escaping's confusing. Keep all your active code in static .js files and use unobtrusive methods like `live()` class-binding to attach to page content.
bobince
Thanks, bobince. I figured encoding the string using json_encode() is way better. Thanks a lot! ;-)
Harvey Diaz