I made a script in Ajax that simply recovers data from MySQL and gives it back to PHP when a select option is changed:
$country = $_POST['country'];
$sql = "SELECT id,name FROM regions WHERE idcountry='$country' ORDER BY name ASC";
$result = mysqli_query($connexion->db, $sql);
$count_row = $result->num_rows;
$regions_arr = array();
while( $row = mysqli_fetch_array($result) ){
$idregion = $row['id'];
$nameregion = htmlentities($row['name']);
$regions_arr[] = array("id" => $idregion, "name" => $nameregion);
}
// encoding array to json format
echo json_encode($regions_arr);
And in my PHP page I have this script:
<script>
$(document).ready(function(){
$("#sel_country").change(function(){
var countryid = $(this).val();
$.ajax({
url: '/include/ajax/getRegions.php',
type: 'POST',
data: {country:countryid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#sel_region").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_region").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Everything works at is has to, except for some of the names recovered that have special characters, for instance "Genève" or "Zürich". Those values are not showed at all, my option has the correct value for the id but it looks empty in the name.
I searched and I tried with uriencode but it doesn't seem to change, any idea how to fix this? Thank you!
UPDATE AND SOLUTION
I solved this by changing my tables to utf8m64 in this way (for each table):
ALTER TABLE
`table_name`
CONVERT TO CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Then in my script Ajax I added this:
mysqli_set_charset($link, 'utf8mb4');
And then it finally works :)