I have an auto-complete script that uses php/jquery to retrieve information from database.
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#artist_name").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
The problem I'm having is displaying html characters "é", "&" and "ó" that are stored in the database as é
&
and é
I cannot get the javascript code to show the html characters for the user to select.
If I change the html entity to the special character in the database, then the auto-complete script stops working altogether.
I found this possible solution on Stackoverflow, but I do not know if how to implement it within the auto-complete javascript that I have or if it will solve my problem at all.
<script>
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
htmlDecode("<img src='myimage.jpg'>");
// returns "<img src='myimage.jpg'>"
</script>
I am not proficient in javascript coding. How can I decode the html entities within the auto-complete script. Please help. Thanks.
Autocomplete.php code:
<?php
$connection = mysqli_connect("localhost","root","root","database_name") or die("Error " . mysqli_error($connection));
//fetch artist names from the artist table
$sql = "select artist_name from artist_names";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['artist_name'];
}
echo json_encode($dname_list);
?>
Please choose one of these (but not both)
PHP Solution :
if you want to decode html entities you could first use php's built-in html_entity_decode()
function in autocomplete.php
:
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = html_entity_decode($row['artist_name']);
}
echo json_encode($dname_list);
JS Solution :
take a look at jQueryUI's doc, you can use this to build your own <li>
element, so that would be something like :
$("#artist_name").autocomplete({
source: availableTags,
autoFocus: true,
_renderItem: function(ul, item) {
return $("<li>")
.attr("data-value", item.value)
//no need to unescape here
//because htmlentities will get interpreted
.append($("<a>").html(item.label))
.appendTo(ul);
}
});