Advertisements

How to send a HTTP GET request to an API endpoint and add the response as HTML elements to the DOM with jQuery

jQuery is a JavaScript library that simplify client-side scripting of HTML.

In case you want to augment your webpage with data from an API endpoint, you may want to look at jQuery.

With this purpose in mind, this post discusses how to send a HTTP GET request to an API endpoint and add the response as HTML elements to the DOM with jQuery.

Planning what to use from jQuery

Before proceeding with writing JavaScript code, it is a good idea to know what we can use from jQuery. With this in mind, let's list the tasks that our code should perform. In short, our code should be able to:

  • Send a HTTP GET request to an API endpoint and read the response.
  • Create HTML elements.
  • Add the HTML elements as children to another HTML element on the same page.

Sending a HTTP GET request to an API endpoint and read the response with jQuery

As I have shown in an earlier post on how to send HTTP post requests and HTTP get requests using jQuery, we can use the jQuery.get() function to send a HTTP GET request to an API endpoint. When the HTTP request is successfully processed by the API endpoint, jQuery.get() will call a function that we had supplied as an input parameter. For example, the following uses jQuery.get() to send a HTTP GET request to /api/v1/items and print data from a successful response to JavaScript console:

$.get('/api/v1/items', function(data) {
    console.log(data);
});

Creating HTML elements with jQuery

Besides finding HTML elements within the Document Object Model (DOM), the jQuery() function can also be used for creating HTML elements. In order to create HTML elements with the jQuery() function, we need to pass a JavaScript string that contains the HTML element tag. For example, the following code segment shows different ways to create HTML elements:

// First example to create <div></div>
$divExample1 = $('<div/>');
// Second example to create <div></div>
$divExample2 = $('<div></div>');
// Example to create <a href="https://www.techcoil.com" target="_blank">Techcoil home page</a>
$linkToTechcoil = $('<a/>', {
    'href': 'https://www.techcoil.com',
    'target': '_blank'
}).text('Techcoil home page');

Adding the HTML elements as children to another HTML element on the same page with jQuery

After creating HTML elements, the next step will be to add them as children to a HTML element on the same page. In order to add an HTML element as a child to another HTML element, we need to use the .appendTo() method. For example, the following code segment adds a h2 element to the HTML element with target-display as the id attribute:

// Creates the h2 element to be added as child element
$h2ToBeAddedAsChildElement = $('<h2/>').text('A child element');
// Adds h2 element as child element to HTML element with target-display as the id attribute
$h2ToBeAddedAsChildElement.appendTo( $('#target-display') );

Summing up with an example

Once we had an idea of what we can use from jQuery to fulfil our task, we can put them together in an example. For the purpose of this guide, let's assume that there is an API endpoint located at /api/v1/websites. In addition, this API endpoint is accessible via the HTTP GET and returns a JSON of the following form as the response:

[
    {'name': 'Techcoil' ,'url': 'https://www.techcoil.com'}, 
    {'name': 'Google' ,'url': 'https://www.google.com'}
    {'name': 'Facebook' ,'url': 'https://www.facebook.com'}
] 

When we receive such a response, we will display a list of links as a child to a HTML element. Additionally, let's assume that this element has target-display as the id attribute.

Once we had the requirements in place, we can proceed to write the JavaScript codes:

$.get( "/api/v1/websites", function( websiteList ) {

    $targetDisplay = $( '#target-display' );
    $unorderedList = $( '<ul/>' );

    // Loop through list of websites
    $.each(websiteList, function(arrayIndex, website) {
        $listItem = $( '<li/>' )
        $linkToWebsite = $('<a/>', {
            'href': website.url,
            'target': '_blank'
        }).text(website.name);

        $linkToWebsite.appendTo($listItem);
        $listItem.appendTo($unorderedList);
    });

    $unorderedList.appendTo($targetDisplay);
});

After the above code segment is executed, the HTML element with target-display as the id attribute will contain the following HTML list:

<ul>
    <li><a href="https://www.techcoil.com" target="_blank">Techcoil</a></li>
    <li><a href="https://www.google.com" target="_blank">Google</a></li>
    <li><a href="https://www.facebook.com" target="_blank">Facebook</a></li>
</ul>
Advertisements

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

Techcoil Recommends

Udemy.com Homepage 300x250
Advertisements
Advertisements