AJAX data showing unformatted HTML

AJAX data showing unformatted HTML

mrsearing-allmrsearing-all Posts: 10Questions: 3Answers: 0

I have used DataTables to displayed DOM sourced HTML-formatted data and it works as expected. List items display as a list, etc.

However, when I have an AJAX source, the data is being displayed with the HTML tags instead of formatting as expected.

data: [{DT_RowID: "row_1", etc.}]
     0: {DT_rowID: "row_1", etc.} 
Items:"<ul><li><strong>None</strong></li><li>Some</li><li>More</li><li>Less</li></ul>"

I expect it to be formatted in the cell like this:

And inspecting the element shows:

<td><ul><li><strong>None</strong></li><li>Some</li><li>More</li><li>Less</li></ul></td>

And this is what the page actually displays:

How do I have DataTables show the formatted HTML?

Answers

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    You are using character entities, ie &lt; which tell the browser to display that character instead of interpreting as HTML. See this doc:
    https://developer.mozilla.org/en-US/docs/Glossary/Entity

    Your data will need to look like the second code snippet. You can use columns.render to replace the entities (&lt;) with the HTML character (<).

    Kevin

  • mrsearing-allmrsearing-all Posts: 10Questions: 3Answers: 0

    Thanks for the response! This is how the data is stored in the database. I had looked at replacing entities but there are so many different possibilties that it would become unwieldy to do that for each column.

    I did end up rendering it correctly with this:

    columns:[
    {
        data: "Items",
        render: function (data, type, row) {
            return $('<div/>').html(row.Items).text();
        },
        autowidth: true
    }]
    
  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    Thats a good solution, much easier than trying to replace the entities :smile:

    Kevin

  • allanallan Posts: 63,678Questions: 1Answers: 10,497 Site admin

    The only issue is that it is slow. If you have a large data set, you'll notice a performance impact due to the DOM operations. String replacement is much faster, but also inherently less complete. If your data set allows for this approach - use it :)

    Allan

Sign In or Register to comment.