Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX and APIs Call the jQuery $.getJSON method

Sandeep Krishnan
Sandeep Krishnan
9,730 Points

This Task 4 in Linking and API from FLicker to my page project, Despite my best efforts I am missing something

I am referring to the last line of code - the callback JSON parameter - Its not passing

$(document).ready(function() {

var weatherAPI = 'http://api.openweathermap.org/data/2.5/weather'; var data = { q : "Portland,OR", units : "metric" }; function showWeather(weatherReport) { $('#temperature').text(weatherReport.main.temp); } $.getJSON(weatherAPI, data, showWeather);

});

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

  var weatherAPI = 'http://api.openweathermap.org/data/2.5/weather';
  var data = {
    q : "Portland,OR",
    units : "metric"
  };
  function showWeather(weatherReport) {
    $('#temperature').text(weatherReport.main.temp);
    $.getJSON(weatherAPI, data, showWeather);


  }

});
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>What's the Weather Like?</title>
  <script src="jquery.js"></script>
  <script src="weather.js"></script>
</head>
<body>
  <div id="main">
    <h1>Current temperature: <span id="temperature"></span>&deg;</h1>
  </div>
</body>
</html>

3 Answers

David Bath
David Bath
25,940 Points

I think this line

$.getJSON(weatherAPI, data, showWeather);

should be outside of the showWeather function.

Sandeep Krishnan
Sandeep Krishnan
9,730 Points

thanks David. It works now. But so should it be outside would you reckon ?

Jacques Wessels
Jacques Wessels
22,557 Points

Hello,

David's right about that line needing to be outside the showWeather function. The three arguments you pass the getJSON method are, in order, the url that you send the request to, the data that gets passed in the request (in this case specifying the city you want the report to be for, and the units of measurement to use), and the final argument is the function to call on success of the AJAX call. So it will only run showWeather after the server's sent a response. If $.getJSON is placed inside the showWeather function, there's nothing telling the browser to actually make the request, and no function will be run.

Hope that helps. :)

Sandeep Krishnan
Sandeep Krishnan
9,730 Points

It does and beautifully so ! Thanks a bunch for a detailed explanation...