0

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.

user5005768Himadree
  • 1,375
  • 3
  • 23
  • 61
  • 2
    Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Mar 27 '18 at 15:00
  • 1
    Is the data on the database in UTF? – RiggsFolly Mar 27 '18 at 15:01
  • @RiggsFolly yes data is in utf-8 format – user5005768Himadree Mar 27 '18 at 15:04

0 Answers0