Questions about Ajax and Get

Questions about Ajax and Get
0

#1

I’m working on the weather app now and I’m testing the waters w/ the code by using the below code:

$("#find_weather").click(function(){
    $.get("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(data, status){
        console.log(data);
        console.log(data[weather][id]);
        console.log(data[weather][main]);
    });
});

#find_weather is the id of a button in the HTML. The URL being used is the example latitude and longitude listed on the page that explains the API link. When I click the button while the website is in progress, at first it printed out the console.log(data); which was all that was inside the function at the time. However, when I debug the code now it skips over the get statement and the console returns this message:

Failed to load https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 503.

Any help is appreciated.


#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

I am not getting the error you mention with your code, but I do get an error with the 2nd and 3rd console.log statements (see below):

        console.log(data[weather][id]);
        console.log(data[weather][main]);

When you use the bracket notation of data[weather], JavaScript looks for a variable named “weather”, but there is not variable named “weather” defined, so you get the error. The same goes for the id and main. I think what you were trying to do was:

        console.log(data.weather[0].id);
        console.log(data.main);

The first console.log above gets the id property of the first element of the array (the value of weather property). The second console.log above gets the value of the “main” property which is an object.


#4

OK, that was what I was testing for because after the first console.log(data) it showed me the contents of the data result. I was making an educated guess about the more detailed displays. I’ll give it another shot but also it gave me the error and skipped the get statement before reaching the console statements after I used the button several times, and persisted after I refreshed the pages.


#5

Update: Made the changes suggested, and after testing the button multiple times still haven’t gotten the error mentioned in the original post. Thanks for the help!