Harvard Extension School, Fall 2018
CSCI E-12 Fundamentals of Web Site Development

## Creating Content with Ajax, jQuery, and JSON

So now we'll bring Ajax into the picture by requesting data from the server. The server will return the seasons JSON data, and we will then pass array of seasons to our function that will create the unordered list.

The jQuery library makes working with Ajax requests very easy. jQuery has a `getJSON` method that makes requesting and receiving JSON data from the server easy. In the simplest case, we'll pass two parameters when we use the `getJSON` method: a URL that will be requested, and a "callback" function that will be called on a successful retrieval of JSON data. A simple case where we make a JSON request to the url "seasons.json" and simply log the data to the JS console looks like:

    $(document).ready(function(){
      $.getJSON("seasons.json",function(data) {
        console.log(data);
      });
    });

- `"seasons.json"`
  This is a relative URL that will be requested.
- `function(data){ console.log(data); }`
  This is the callback function that is called when the JSON request is successfully completed. Note the `data` is the data from the JSON request.

Example of getJSON in JSFiddle

### All together

So we take our previous example, where we built a list from a JSON data structure, and change it so that the JSON data comes from an Ajax request (using the `getJSON`) method of jQuery:

- Example in JS Fiddle
- Live Example | download

Copyright © David Heitmeyer