Javascript Lesson 4: Ajax

Ajax (or Asynchronous Javascript And XML) is used to update your web pages with information from an external source. It works by having your browser send a request to an external server for data, and once retrieved, it will update a section of your webpage with the formatted data.

In this example, we will use an AJAX script to retrieve a picture from NASA's picture of the day web page. The retrieved image will be displayed on our page, and will update whenever the image is changed on NASA's website.

-Lines 1 through 3 start with a link to an external script known as an API. An API is a set of instructions that can be used to build software or perform various functions.

The API we have linked allows us to perform AJAX operations. The code to perform these routines has been done for us already, and to utilize it, all we have to do is provide a link to the script. This is a shortcut we can use so that we don't have to write out all of the instructions ourselves.

-Lines 5 through 7 create the three elements we will need to display our retrieved data. We create a header element to display the title of the photo, an image to house the retrieved image, and another header to display the credits for the photographer/artist.

Each element has been given an ID that will be referenced in the code.

-Lines 10 and 11 create a variable with a link to an additional API. This API lets us pull images from NASA's website. For some API's, the developer will require you to register or pay for an API key. The key for this API however has been provided for free and it requires no registration.

-Line 13 starts with the creation of our AJAX script "$.ajax()"

-Lines 16 and 17 contain the location of our API script (the variable url that we created earlier), and the start of our "success" function. If we are successful in retrieving data, the rest of the code contained in the function will initiate. The statement "result" contained within the parentheses, will house our retrieved data.

-Line 20 contains an if statement that checks for an image title in the retrieved data. $("#title").text refers to our header element with the ID of "title", and ("Title: " + result.title); appends the retrieved data to our header.

-Line 25 functions the same way as the previous if statement. We search for data labeled "copyright" and then append it to our appropriate header element.

-Line 31 takes our img element with the ID of "apod_img_id" and adds the retrieved image from our result.

To use this program, copy the code from the right into the body of your website.