I would like to use a Geolocation API on the client-side to identify the user's IP and add their state to my webpage. As I am fairly new to learning Javascript and jQuery, could you assist me with my problem below?
I am receiving an error from the Console that $ is not defined – how do you suggest I solve this problem so the solution works? (see near end of script)
Additional Issues:
- I would like the user's state to render at the same time as the surrounding text appears –– how do I accomplish this?
- I tested the API with a VPN and found a few inaccuracies –– is it more difficult for API's to track IP (and determine their state) when the user uses a VPN to be in California vs. if they were actually in California? (California is used as an example)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Get User State & Display</title>
<script src="https://cdn.jsdelivr.net/npm/ip-geolocation-api-jquery-sdk@1.1.0/ipgeolocation.min.js"></script>
<script>
_ipgeolocation.enableSessionStorage(true);
var ip = sessionStorage.getItem("ip");
var country_name = sessionStorage.getItem("country_name");
var state_prov = sessionStorage.getItem("state_prov");
if (!ip || !country_name || !country_code2) {
_ipgeolocation.makeAsyncCallsToAPI(false);
_ipgeolocation.setFields("country_name, state_prov");
_ipgeolocation.getGeolocation(handleResponse);
}
function handleResponse(json) {
ip = json.ip;
country_name = json.country_name;
state_prov = json.state_prov;
}
$("document").onload(function() {
$('.state').html(json.state_prov);
});
// I am receiving an error from the Console that $ is not defined – how do you suggest I solve this problem so the solution works?
</script>
</head>
<body>
<p><strong>If you would like to know more about stock options in <span class="state"></span>, contact our team today!</strong></p>
</body>
</html>