1

I am currently working on a website that displays the current weather in your location. I am using the API https://openweathermap.org/current#geo provided by freecodecamp. I made an .ajax() call however my url has to dynamic according to the user's url. However, the .ajax() call does not recognize the variables. What am I doing wrong?

//jQuery is active
 $(document).ready(function(){
  //latitude and longitude found
 if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
    var userLon=position.coords.longitude;
    var userLat=position.coords.latitude;
    console.log(userLon);
    console.log(userLat);
  });
 };//navigation bracket

 $.ajax({
      url:"api.openweathermap.org/data/2.5/weather?lat="+userLat+"&lon="+userLon,
      success:function(doc){
       //the weather is displayed on html
}
   });//ajax call bracket
 });//jQuery bracket
Hasanat Jahan
  • 11
  • 2
  • 3

1 Answers1

0

Its an issue with the async request. Move the ajax call within the if condition

$(document).ready(function(){
  //latitude and longitude found
 if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
    var userLon=position.coords.longitude;
    var userLat=position.coords.latitude;
    console.log(userLon);
    console.log(userLat);

     $.ajax({
      url:"api.openweathermap.org/data/2.5/weather?lat="+userLat+"&lon="+userLon,
      success:function(doc){
       //the weather is displayed on html
      }
   });//ajax call bracket
  });
 };//navigation bracket


 });//jQuery bracket
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400