I want to fetch words in different languages and display them to the typehead. Here is the Ajax code: [all other codes e.g html are set correctly.]
$(document).ready(function(){
$('#country').typeahead({
source: function(query, result)
{
$.ajax({
url:"test.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
And Here is the php code
<?php
header('Content-Type: json; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if (!$con->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $con->error);
exit();
} else {
printf("Current character set: %s\n", $con->character_set_name());
}
$request = mysqli_real_escape_string($con, $_POST["query"]);
$query = "
SELECT e.id, e.name
FROM test_db.employees as e
WHERE e.lang_code='hindi' AND e.name LIKE '%".$request."%'
";
$result = mysqli_query($con, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[$row["id"]] = $row["name"];
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
}
?>
I checked in the browser inspect element and found that php correctly getting all the values in utf-8 format from mysql.But Ajax is not geting it.But if i remove $con->set_charset("utf8") then Ajax got it in only English But for other language it display ?????? format. i thing after fetching the elements in php array, it is not correctly encoded in utf-8 format. please help me.