• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 4/2/20

Request data from a backend

In this chapter, we are going to make our first HTTP request to a server with AJAX.

What is HTTP?

Put simply, HTTP is a protocol which allows us to send information around the web.  For example, when your browser asks for http://www.openclassrooms.com, it is actually sending an HTTP request and then handling the response (the OpenClassrooms homepage).  HTTP requests come in different flavors, using different verbs (GET, POST, PUT, and DELETE are the four most common).  The kind of request your browser makes (and the kind we will use in this chapter) is a GET request.  A GET request generally means we would like the server to send us some data.

Don't worry too much about the details for now: once you've seen HTTP requests in practice, it becomes a lot easier to understand.

What is AJAX?

AJAX stands for Asynchronous JavaScript And XML.  Now there's a mouthful.

Basically, it is a system that allows us to send requests and handle the responses from within our JavaScript code.  For example, when you leave a comment on a blog post, when you send or receive e-mail on a webmail service like Gmail, or when a webpage updates itself without refreshing, it is often using AJAX to do so.

Let's have a look at how to use AJAX in JavaScript to send a GET request to a server, and how to handle what it sends back.

Sending a request

All this theory may seem complicated and hard to understand, so let's get down to actually building and sending a request to see how it all works.

Practice!

Head to CodePen Exercise P2CH3a and follow the instructions below.

The objective of this new, simple app is to use openweathermap.org's API to find the current weather in the city requested by the user.

  1. First things first, let's build the object that will do all of our request work: an XMLHttpRequest. Add the following line: let apiRequest = new XMLHttpRequest();.

To prepare and send our request, we'll use two methods: open() and send():

  • the open() method sets the type of request and the URL it will be sent to,

  • the send() method then sends the request.

Seeing as we need the information from the text input to send our request, we will call these methods in the form's submit listener.

  1. Add a listener for cityForm's submit event that prevents the default behavior.

  2. Add a constant chosenCity to the listener, containing the value entered in the city input field.

  3. Now add the following two calls to the listener:

    apiRequest.open('GET', 'https://api.openweathermap.org/data/2.5/weather?q=' + chosenCity + '&APPID=b34fddd3dae4a2eb0ad363b62f98ba1e');  apiRequest.send();

The open() call sets the request type to GET and the URL to the appropriate API endpoint, and the send() call sends the request. In the next exercise, we'll look at how to capture and handle the data returned by the API.

Once you've given it a go, watch me code a solution and see how your approach compares:

Handling data returned by a request

Now that we have built and sent our request, we need to see how to capture and handle the data returned by the server.

Practice!

Head to CodePen Exercise P2CH3b and follow the instructions below.

To capture data returned by a request, we need to add something to our XMLHttpRequest object: an onreadystatechange function. An XMLHttpRequest has a readyState property that changes from 0 to 4 as the request progresses, and the onreadystatechange function is called at each change. When the readyState hits 4, the request is complete and the response is fully received.

  1. Let's start building our onreadystatechange function. Add the following just after the declaration of apiRequestapiRequest.onreadystatechange = () => {};.

  2. Seeing as we only want to access the response data if we are sure it has arrived, we shall only execute code if the request's readyState is 4. Add the following if statement, which will contain all of our logic: if (apiRequest.readyState === 4) {}.

  3. Now we know that the request's response object is populated. The openweathermap.org API returns JSON, but our request object receives it as text. We therefore have to parse it to make it a useable object in our JavaScript code.Add this line (inside our if statement, of course) to capture the server response:  const response = JSON.parse(apiRequest.response); .

  4. The response constant now contains the full object returned by the server. Let's now extract the information we need and show it in the DOM. We are going to extract the name of the city and the main weather description. As per the openweather.org documentation, we will extract the name value for the city name and the weather[0].description value for the weather description. Set the report section's text content with the following line:

    reportSection.textContent = 'The weather in ' + response.name + ' is ' + response.weather[0].main + '.';. Enter your city and watch it work!

  5. However, there is a common error case we have not dealt with. What happens if the user enters a city that is not in openweathermap.org's database? From the API's point of view, if it receives a request for a city it does not recognize, it returns a 404 error. But that's awesome news! We can check for 404 errors and print an error message! Before declaring the response constant, add an if statement that checks apiRequest.status. If it is 404, set the report section's text content to an error message and make sure the rest of the function is not executed.

Once you've given it a go, watch me code a solution and see how your approach compares:

Saving data in the browser

Modern browsers allow us to temporarily store small amounts of data for later use.  There are two main methods: local storage and session storage.  Session storage is emptied when the browser window is closed, whereas local storage remains untouched.  While we don't need it for the app we have built here, it can come in handy in more complex apps.

Let's recap!

In this chapter, we covered how to prepare, build, and send an HTTP GET request with AJAX, using an  XMLHttpRequest object.

Example of certificate of achievement
Example of certificate of achievement