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();
              }
          });
      }
  });
jncraton
  • 9,022
  • 3
  • 34
  • 49
Matteo Mosconi
  • 244
  • 5
  • 19

2 Answers2

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.

Community
  • 1
  • 1
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
0

Your question is similar to this.

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

Escaping HTML strings with jQuery

Community
  • 1
  • 1
Loken Makwana
  • 3,788
  • 2
  • 21
  • 14