Skip to Main Content

Kelbe Fox ID226

Advanced Web Scripting

Ajax Exercise

Ajax or Asynchronous JavaScript and XML is a technique that allows developers to update a webpage with data from a web server without reloading the page. To send a request, JavaScript uses a browser object called the XMLHttpRequest (XHR) object or it can use Fetch API. These requests are often made to web services which provide Application Programming Interfaces or API.

The way a normal HTTP makes a request is the browser makes an HTTP request for an entire page, the server returns an HTTP response for the page, and the browser loads the entire page. With an Ajax request the browser uses JavaScript to send an asynchronous request to the server, the server returns the requested data in a response, and the web page uses JavaScript to update the DOM with new data. This means the browser doesn't need to refresh the page to add the data.

The two most common data formats for Ajax are XML (Extensible Markup Language) and JSON (JavaScript Object Notation). Both of these formats use text to store and transmit data. Out of the two, JSON is more popular because it's more human friendly to read. This is also why you will see a lot of server-side languages provide methods for encoding data into JSON. JSON also uses less memory than XML because it is more succinct.

API's are constructs made available in programming languages to allow developers to more easily create complex functionality. Fetch API is considered the best practice for new development. Fetch API uses the fetch(url) method to make an asynchronous GET request to the URL. It then returns a Promise object that will eventually return a Response object. A promise object has three states: pending, fulfilled, and rejected. The Promise object is pending when it is first created, fulfilled when it returns a value, and rejected if an error occurs. Whether it returns a value or an error, it is considered settled. Response objects use the method json(). This method returns a Promise object that eventually resolves to a JavaScript object that's created from the JSON that's returned by the asynchronous request.

In this exercise, we used Ajax to fetch data from an API containing lots of photos and some info about each photo. The page allows users to select which photo they want to view.

Click here to test the photo-viewer!