1

My script receives some data from a PHP page. One item called "content" contains HTML code. I have to put my HTML code in a div but unfortunately, it is appended as plain text. How can I append it to the DOM as real HTML? This is my jQuery code:

      $.ajax({
      'url': 'ajaxdashboard.php',
      dataType: 'json',
      cache: false,
      success: function (json) {
          $.each(json, function (key, value) {
              for (i = 0; i < value.length; i++) {
                  $('#arguments').append('<div class="well student" style="display: none;" id="post-' + value[i].id + '"><h3>' + value[i].title + '</h3><span>Published by <font color="blue"><b>' + value[i].name + ' ' + value[i].surname + '</b></font></span><br><br><span id="post-content-' + value[i].id + '"></span></div>');
                  $('#post-content-' + value[i].id).html(value[i].content);
                  $('#post-' + value[i].id).fadeIn();
              }
          });
      }
  });
7
  • This is a little ambiguous to me. Are you trying to display the returned content as HTML (i.e. the user will see the tags)? Or do you want to render the HTML? Commented Oct 7, 2012 at 12:11
  • I have to display as html, user should see the result in rendered html :) No tags at all! Commented Oct 7, 2012 at 12:14
  • 1
    The code looks okay to me. Are you using <pre> or <code> tags by any chance? Commented Oct 7, 2012 at 12:15
  • Is the problem with #arguments or #post-content ? Does value[i].content come back html encoded? Commented Oct 7, 2012 at 12:15
  • Is your html code is encoded means do it contains characters &lt; &gt; &#32, &nbsp; etc.. Commented Oct 7, 2012 at 12:18

2 Answers 2

1

You're problem is that the PHP is returning encoded html. < in html is <. Therefore that's what the user will see.

Update your PHP to return the original HTML. Otherwise you can cheat it with jQuery something like this:

$('#post-content-' + value[i].id).html($(value[i].content).text());

Source for decoding html.

Sign up to request clarification or add additional context in comments.

Comments

0

Your question is similar to this.

use text() instead of html() that escapes automatically.

Escaping HTML strings with jQuery

1 Comment

text() won't render html in DOM

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.