This code is for getting selected country value in dropdown with country flag in it using ip address of the server and by using google plugins ..
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<?php
// $ip_address = '1.7.255.255';//you can use the ip address manually like this
$ip_address = $_SERVER['REMOTE_ADDR'];
$geopluginURL = 'http://www.geoplugin.net/php.gp?ip=' . $ip_address;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
$country = $addrDetailsArr['geoplugin_countryName'];
if (!$country)
{
$country = 'Not Define';
}
echo '<strong>IP Address</strong>:- ' . $ip_address . '<br/>';
echo '<strong>Country</strong>:- ' . $country . '<br/>';
$url = "https://api.ipgeolocationapi.com/countries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if (!$json)
{
echo curl_error($ch);
}
curl_close($ch);
$data = json_decode($json); // getting response of json in variable $data
?>
<select id='selUser' style='width: 200px;'>
<?php
foreach ($data as $key => $value) // then to find a value of a data
{
?>
<option <?php echo $value->name == $country ? 'selected' : null ?> value="<?php echo $value->name; ?> " data-iconurl="https://www.countryflags.io/<?php echo $value->gec ?>/flat/64.png"> <?php echo $value->name; ?></option>
<?php
}
?>
</select>
</body>
</html>
<script>
// use template result=> for having a flag in dropdown
// and use selection for getting it selected flag icon with dropdown selected
$("#selUser").select2({
templateResult: function (state) {
var iconUrl = $(state.element).attr('data-iconurl');
if (!state.id) {
return state.text;
}
var baseUrl = iconUrl;
var $state = $(
'<span><img src="' + baseUrl + '" class="img-flag" width="30px"/> ' + state.text + '</span>'
);
return $state;
},
templateSelection: function (state) {
var iconUrl = $(state.element).attr('data-iconurl');
if (!state.id) {
return state.text;
}
var baseUrl = iconUrl;
var $state = $(
'<span><img src="' + baseUrl + '" class="img-flag" height="17px"/> ' + state.text + '</span>'
);
return $state;
}
});
</script>
idioma.value
instead ofidioma.id
maybe? – Vonnie