JavaScript AJAX Basics (retiring) AJAX and APIs Displaying the Photos

Carie Pigeon
Carie Pigeon
7,892 Points

Flickr API Code Question

In the Flickr API project in the AJAX course the instructor uses function displayPhotos(data) { I see that earlier we defined our wanted search to be var animal = $(this).text(), which grabs the keyword from the button element that is clicked on. Then we define var flickrOptions = { tags: animal, format: "json" }; I understand all of this. But then we go on to code: function displayPhotos(data)... I'm not sure what the "data" argument is, it hasn't been explicitly defined in the code beforehand. Is the "data" argument pointing to the json file received? Thanks!

1 Answer

28,391 Points

Strictly speaking data is a parameter, not an argument. Parameters are variables whose value is set by the argument that is passed in when the function is called. So the data parameter will contain whatever argument the displayPhotos function is called with. So the real question is where is the function called?

Well the answer is that it is called by jQuery itself because you pass the function into the getJSON jQuery method:

$.getJSON(flickrAPI, flickrOptions, displayPhotos)

The getJSON method takes three arguments. The first is the URL where the request should be sent, the second is the data that should be sent to the URL, and the third is a callback function which will be called when the request succeeds.

By looking at the documentation of the getJSON method (linked above) you can see that the first argument it passes into the function (and therefore the one the data parameter is set to) is the data that it received from the request. Which will indeed be the JSON that flickr sends in response.