Andy Andy - 4 months ago 8
Javascript Question

Everything works but the Ajax

Making a call to the openweather API. When I input the URL into a browser, I can see the JSON object. However my ajax below is not allowing anything to appear in my HTML. Even if I want to document.write the entire json object, I cannot. I can output the lat and long just find so the geolocation is working. Not sure what's wrong with this code.

Here's the HTML:

<body>
<div class="container">
<div class="col-lg-12 header">
<h1>My Location</h1>
</div>
<div class="row text-center box">
<div class="col-lg-12" id="data">Lat Long</div>
</div>
</div>
</body>


Here's the JS:

$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(main);
}
});
function main(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=edb786f28101411599bcf4bfc8b6edbc";
$.ajax({
dataType: 'json',
url: api,
success: function(data) {
city = data.name;
$("#data").html(city);
}
});
}

Answer

Try $.getJson instead of $.ajax: $.getJSON( { dataType: 'jsonp', url: api, success: function(data) { city = data.name; $("#data").html(city); }

In the HTML, make sure to add jquery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script> <script src="a.js"></script> // whatever your js file is named

Without modifying your code, the page asked to access my location and then displayed my current city. I'm not sure what it is supposed to output though. What are you expecting the output to be?

Comments