I’m trying to display a specific image based on the country the user is visiting my site from. I’ve managed to use ajax and the https://geolocation-db.com/jsonp/ to capture the location information.
If I check this from the US, or any other country, I’m able to output that country (using TunnelBear), but my goal is to display a different image depending on the output country.
What am I missing?
JavaScript
x
19
19
1
//get ip, city, state & country
2
$.ajax({
3
url: "https://geolocation-db.com/jsonp",
4
jsonpCallback: "callback",
5
dataType: "jsonp",
6
success: function (location) {
7
$("#country").html(location.country_name);
8
},
9
});
10
11
let getCountry = location.country_name;
12
13
if (getCountry == 'United States') {
14
bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED STATES">`;
15
} else if (getCountry == 'United Kingdom') {
16
bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED KINGDOM">`;
17
} else {
18
bg.innerHTML = `<h3>This is not working!</h3>`;
19
}
JavaScript
1
4
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<div id="country"></div>
4
<div id="bg"></div>
Advertisement
Answer
You need to check the country inside the success method.
JavaScript
1
18
18
1
//get ip, city, state & country
2
$.ajax({
3
url: "https://geolocation-db.com/jsonp",
4
jsonpCallback: "callback",
5
dataType: "jsonp",
6
success: function (location) {
7
$("#country").html(location.country_name);
8
let getCountry = location.country_name;
9
10
if (getCountry == 'United States') {
11
bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED STATES">`;
12
} else if (getCountry == 'United Kingdom') {
13
bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED KINGDOM">`;
14
} else {
15
bg.innerHTML = `<h3>This is not working!</h3>`;
16
}
17
},
18
});
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="country"></div>
3
<div id="bg"></div>