Getting Started with jQuery (Part 4): Consuming External Data Through API

In this fourth part, of our five parts jQuery tutorial, we look at how jQuery allows us to consume external resources and APIs. jQuery has an in-built library which takes care of all the low-level coding that is required to communicate with resources that are hosted by other people. In this tutorial, we will make use of jQuery AJAX functions to talk and exchange information with other external resources.

If you have missed our previous tutorials on how to use jQuery to manipulate the HTML elements on the screen, you can refer to them below:

AJAX? API? What?

Before we dive into this tutorial, let’s find out more about some of the terms which we will be exposed to.

AJAX

AJAX stands for Asynchronous JavaScript and XML. It is used by web clients like your web browser to create asynchronous web applications. This means that with AJAX, your web browser can communicate with external services by sending and receiving data in the background, responding to events that your user has entered. The difference between traditional server-client applications is that the page content is dynamically rendered while new data is fetched in the background. This is done without contacting the application server and ending it as HTML for your browser to display.

API

API stands for Application Program Interface. An API will state what services are available to use and the instructions on how to use them. For example, a weather station website may publish a set of API stating what sort of weather metrics they are tracking and give examples of how to use each of the API to get or query the data from their system. This API could look like this. jQuery can then communicate with it to retrieve data and display the data on your site.

What Will We Be Building?

We will be building a country search and lookup tool. In this lookup tool, we allow the user to enter a partial string and search it against the API provided by RestCountries.eu. We will then display the search results from the list of matched countries. The user can also click on any country returned from the search result to see the country details like the native name, timezone information, latitude and longitude, region and sub-region, and currencies that are used in the selected country.

Building Our Search Input Form

Let’s build a simple search input form to allow the user to input the country which he wants to search. After he has entered his search term, there should be a button for him to click to start searching. In the particular screen, there should also be a list box to display the search results and for the user to click to see more details of the selected country.

Our starting HTML skeleton code looks like below:

And our starting CSS looks like this:

Our rendered HTML output looks like this:

Coding the Search Function

We will now handle the “Search” button click to retrieve the text from the input text field before we can send it to the external service for querying. Do you still remember how to get the value from an input text field? Code for comparison below (Remember we need to check if there are more than 4 characters) :

The code above checks whether the input value which is assigned to “inputSearch” is more than 4 characters. If it is shorter than 5 characters, then there will be a display prompt to ask the user to enter more than 4 characters.

Examining the API

Next, let’s take a closer look at the API which we will be querying. Navigate to REST Countries-Search by Name. The syntax for searching by country name is:

An example of a search for the country “Belgium” would look like this:

Let’s see what kind of result is returned when we issue that command. When the URL is entered into a web browser, the REST Countries API returned a JSON result. In short, JSON stands for JavaScript Object Notation, which is a uniform way for API to exchange data. The other common way would be XML.

The JSON result gives us a tree-like structure for our code to read so we can extract information out of it.

The first row “0” represents the current element that is displayed in the tree. As we are doing a partial string search, there could be more than one country match being returned. This will be labeled “0” for the first country, “1” for the second country and so on.

For this tutorial, we are interested in extracting the value for both the name and native name of the country, the timezone information, co-ordinates for the country and currency used.

The mapping for these values against the JSON result is shown below:

  1. Name of country – “name” field

  2. Native name of country – “nativeName” field

  3. Latitude and Longitude of country: first element of “latlng” and second element of “latlng” field

  4. Currency of country – “currencies” field

jQuery AJAX Functions

We are now typing the URL manually into our web browser to see the result. How do we get jQuery to connect to the remote API and fetch the data through code?

We can make use of jQuery in-built AJAX functionality via the “$.ajax” function to interact and retrieve data from external resources. The syntax for jQuery AJAX function looks like this:

The above code has 3 important parts to it. First is the “method“, which refers to what kind of HTTP verb you want jQuery to use when connecting to the external resource. Common verbs include GET, which is commonly used to retrieve data and POST, which is commonly used when you need to send data to the server.

Second is the “URL” of the remote resource. In the example above, the URL will refer to https://restcountries.eu/rest/v2/name/belgium if we want to search for Belgium.

Last is the “done” function. jQuery will invoke the code in the “done” portion once it has done fetching data from the remote resource. The “msg” variable in the code above will contain the contents of the fetched data.

Parsing and Displaying the Results in the List Box

Let’s improve our jQuery code to include the AJAX function above and communicate with the external API. We need to get the input value from the user and concatenate it with the URL of the external resource and send it to the server for searching.

After that, we will need to include code in the “done” portion to store the returned result into an array so we can access it once the user clicks on a particular matched country.

Your jQuery code should look as follows:

Display the Matched Countries in the List Box

We will now add a list box so that we can show the search results and also present an interface for the user to select which matched countries he would like to see more details on.

First, we add a list box to our HTML code.

Next, we modify our jQuery code which will populate the contents of the list box once we have our search results back from the external resource.

Now, when you type a country in the search box and click on the “Search” button, your list box will get populated by the search results.

Exercise 1: Displaying the Details of the Selected Country

We have been keeping all the details of the searched countries in our array of objects named “searchResults“. Let’s improve our jQuery code to listen to the item click event on our list box so that we can display the country detail that the user selects.

Can you figure out what the code should look like for this functionality to happen?

To do that, we add a click listener to our list box. When the user selects an item from our list box, we capture the index of the clicked item and retrieve the element from our “searchResults” array and display it.

Exercise 2: Doing Housekeeping for a New Search

Let’s add a reset button so we can clear the search results and the input text field to allow the user to enter a new search term.

When the reset button is clicked, the jQuery code should do the following:

  1. Clear the search input text field

  2. Clear all the items in the list box (Hint: you can use the .empty() function on the list box)

  3. Hide the detail panel “detailpanel” (Hint: you can use the .hide() function)

Try out this exercise yourself before referring to the solution below!

Got stuck? This is how we can do it:

HTML Code:

CSS Code:

The new function in jQuery:

Did you get it right? If so, congratulations! If not, you can refer to the completed solution here.

In our next tutorial, we will learn how to use jQuery to create a real-time chat room where multiple users can enter a chat room and messages sent to the chat room by one user will be broadcasted immediately to all the users in the chat room.

CategoriesTags

Related Posts