Middi
Middi

Reputation: 353

API accepts URL but won't accept URL in a variable

I want to be able to dynamically generate my API queries using location.

if I console.log out my geolocation and copy that to my ajax API URL it works as it should.

However, the moment I try to pass the URL a variable with the string in it, it stops working.

So when I remove the ajax URL and replace it with the geoAddress variable, which contains the same URL, it stops working.

Here's the codepen http://codepen.io/Middi/pen/peLMBQ

Here's my code.

var geoAddress;

$(document).ready(function ($) {

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {

        geoAddress = "http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&units=metric&appid=6776250c9f90718881dbecfc4c7c5319";

    });
}


$.ajax({
    url: geoAddress,
    success: function (parsed_json) {
        var location = parsed_json.name;
        var country = parsed_json.sys.country;
        var temp_c = Math.round(parsed_json.main.temp);
        var description = parsed_json.weather[0].description;
        var icon = parsed_json.weather[0].icon;


        // Add to Dom
        $('.weather-place').html(icon + "<p>" + location + ", " + country + "</p><p>" + temp_c + "°C</p>" + "</p><p>" + description).fadeIn(400);

    }
});
});

Upvotes: 0

Views: 28

Answers (1)

RAJNIK PATEL
RAJNIK PATEL

Reputation: 1049

Error arrive in your code because AJAX call instantly fire without waiting for over IF condition. That's why when Ajax call fire it's receive blank value in variable geoAddress

Try this way it's work :

var geoAddress;

$(document).ready(function ($) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {

            geoAddress = "http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&units=metric&appid=6776250c9f90718881dbecfc4c7c5319";

            $.ajax({
                url: geoAddress,
                success: function (parsed_json) {

                    var location = parsed_json.name;
                    var country = parsed_json.sys.country;
                    var temp_c = Math.round(parsed_json.main.temp);
                    var description = parsed_json.weather[0].description;
                    var icon = parsed_json.weather[0].icon;

                    // Add to Dom
                    $('.weather-place').html(icon + "<p>" + location + ", " + country + "</p><p>" + temp_c + "°C</p>" + "</p><p>" + description).fadeIn(400);
                }
            });

        });
    }
});

Upvotes: 1

Related Questions