I am retrieving data encoded from database by htmlentities(), decoding it by html_entity_decode() and displaying them on the html page. If I echo the decoded data on the page, it displays correctly. However, if I pass the decoded data to a data-* attribute and retrieve it by jQuery, the displayed (decoded) data has html tags. I have highlighted the important steps of my code here:
// data retrieved from my WYSIWYG text editor
$content = "Which one of the following statements is true about the number of faces and edges<div>of a square based pyramid?</div>";
// encode form content and store in the database
$encodedcontent = htmlentities($content, ENT_QUOTES, 'UTF-8', false);
/** The way data is stored in db: Which one of the following statements is true about the number of faces and edges<div>of a square based pyramid?</div> **/
// retrieve the same content from the database and decode it
$contentFromDb = html_entity_decode($encodedcontentfromdb);
// now display $contentFromDb in html
// first output displays correctly as expected
<div><?php echo $contentFromDb; ?></div>
store php variable in data-* attribute to retrieve in jQuery
<div id="modalcontentlink" style="display:none" data-dbcontent="<?php echo $contentFromDb; ?>"></div>
use jQuery to retrieve data-dbcontent attribute value
$(document).ready(function() {
$("#modalcontentlink").click(function(){
var dbContent = $(this).data('dbcontent');
// display in bootstrap modal
$("#modal-dbcontent").text($dbContent); // #modal-dbcontent represents id of the div element in which am displaying the content
});
});
The second output is:
Which one of the following statements is true about the number of faces and edges<div>of a square based pyramid?</div>
Would someone please shed light on why the second output still has html tags? Greatly appreciated. So after some research, I learnt that jQuery gives you whatever you entered as a string, hence the display of html tags in the output. I followed this suggestion
$(document).ready(function() {
$("#modalcontentlink").click(function(){
var dbContent = $(this).data('dbcontent');
// display in bootstrap modal
$result = $('<div/>').html(dbContent).text();
$("#modal-dbcontent").text($dbContent); // #modal-dbcontent represents id of the div element in which am displaying the content
});
});