Community Post

How To Request For Data Over The Internet With JQuery AJAX

Kwabena Berko

One of the most common task for any web developer these days is to request for some sort of data over the Internet.

It is therefore paramount for us as web developers to acquire such a skill. There are many tools or frameworks that allow us to perform this task with little to no hustle.

In this tutorial though, we will focus on using jQuery to communicate and retrieve data from an external server.

Prerequisites

This tutorial is intentionally aimed at any beginner who has a basic understanding of HTML5, CSS3 and Javascript.

JQuery

As summarised perfectly on their official website, jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax very simple with an easy-to-use API that works seamlessly across a wide array of web browsers.

Tools

Bootsrap 3, for our user interface. This is the go-to CSS framework for most web developers as it helps to rapidly build awesome UI's. You can download the compiled and minified files directly from their website or use their CDN link.

JQuery. This is the most important tool for our application as we will exclusively use it to make AJAX request to our server to request for data. Again, download it directly from the website or use the appropriate CDN link.

The data we will be using will be from a simple footballers REST API I built purposely for this tutorial. This API responds with with a list of footballers in a JSON format. JSON, derived from JavaScript Object Notation is a syntax for storing and exchanging data. It is now the preferred data-exchange format by most web developers, overtaking the likes of XML as it is light-weight and very easy to read. JSON data is usually in the form of keys and values, where data is typically separated by commas. Curly braces hold objects whereas square brackets hold arrays.

An example response from the footballers API is as follows:


{

    "success": true,
    "message": "Brief Profiles of Footballers",
    "footballers": [
        {
            "name": "Lionel Messi",
            "club": "Barcelona",
            "age": "29",
            "position": "CAM / ST",
            "nationality": "Argentina",
            "imageUrl": "http://res.cloudinary.com/kwabena/image/upload/v1483669370/messi_s7kwji.png"
        },
        {
            "name": "Cristiano Ronaldo",
            "club": "Real Madrid",
            "age": "31",
            "position": "LW / ST",
            "nationality": "Portugal",
            "imageUrl": "http://res.cloudinary.com/kwabena/image/upload/v1483669370/ronaldo_ta401m.png"
        },
        {
            "name": "Gareth Bale",
            "club": "Real Madrid",
            "age": "27",
            "position": "RW",
            "nationality": "Wales",
            "imageUrl": "http://res.cloudinary.com/kwabena/image/upload/v1483669370/bale_snfqse.png"
        },
        {
            "name": "Andres Iniesta",
            "club": "Barcelona",
            "age": "32",
            "position": "CAM / CM",
            "nationality": "Spain",
            "imageUrl": "http://res.cloudinary.com/kwabena/image/upload/v1483669370/iniesta_rmnyst.png"
        }
    ]

}

Project Structure


- ajax-request/
----- css/
---------- bootstrap.min.css
----- js/
---------- jquery-3.1.1.min.js
---------- app.js //This is where the application logic goes
----- index.html

Let's Get Started

Let's begin by declaring the HTML and CSS for our application in our index.html file. Open it in your favourite text editor (I am using Sublime Text 3) and type in the following code:


<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset="utf-8">
    <title>Ajax Request</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> 
</head>
<body>

<style type="text/css">
        body {
            font-family: 'Open Sans';
            padding-top: 50px;
            padding-bottom: 50px;
            background: #DEDEDE;
        }

        .footballer-card {
            background: #FFF;
            margin-bottom: 0.5em;
            margin-top: 0.5em;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0px 0px 3px #CCC;
        }

        p.footballer-details {
            margin-top: 1.6em;
        }

        .footballer-card span {
            margin-left: 0.5em;
        }

        img.footballer-img {
            width: 90px;
            border: 3px solid #CCC;
            border-radius: 100%;

        }
    </style>

    <div class="container">

        <div class="col-md-12">
            <div class="col-md-6 col-md-offset-3">

                <div id = "main">

                <!-- Footballer list item goes here -->

                </div>

            </div>
        </div>
    </div>

<script type="text/javascript" src = "js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src = "js/app.js"></script>

</body>
</html>

Open your app.js file in the js folder. This is where all the magic is going to happen :) Lets first define our ready() event.This event occurs when the DOM (document object model) has been loaded. Lets also get our main div element by its id and store in a variable named "main" .


$(document).ready(function(){

   //Logic goes here
   var main = $("#main");

});

In the $(document).ready () function, lets make a GET request to our server to retrieve the details of footballers. GET is an HTTP verb that is used to obtain or read data from a RESTful Webservice. Other HTTP verbs include:

POST, used to create a resource

PUT, used to update or replace a resource

and DELETE, used to delete a resource

Add the following to your app.js file:


//Logic goes here
var main = $("#main");

   $.ajax({
    url: 'http://pure-forest-79660.herokuapp.com/footballers',
    type: "GET",
    dataType: 'JSON',
    success: function(response){
        console.log(response);
    }
   });

Here, we are using jQuery's ajax method and passing in the required parameters, such as the url , the method type , in this case GET, because we are just retrieving or reading the data. We also chose JSON as our preferred data type as our response from the server is in that format.

We have a success callback function that currently logs the response to our console. Refresh your browser and open the console and you should see something like this:

Object { success: true, message: "Brief Profiles of Footballers", footballers: Array[10] }

You can now delete the console.log(response) line or comment it out. I will be deleting mine.

Before we do anything else, lets check to see if the request was successful. If it was indeed successful, we declare a variable called footballers and assign it to the response's football array, response.footballers. On the other hand, if the request was unsuccessful, we alert the user about it.


//Logic goes here
var main = $("#main");

 $.ajax({
    url: 'http://pure-forest-79660.herokuapp.com/footballers',
    type: "GET",
    dataType: 'JSON',
    success: function(response){
        if (response.success) {
            var footballers = response.footballers;
        }
        else{
            alert("Oops, an error occured fetching the profiles.");
        }
    }
   });

Great, thats how simple it is to make a GET request with JQuery AJAX!

Let's use the data we have now to update our user interface. We are going to write a for loop that will loop over the footballers array and display a list of footballers with each footballer item having an image, a name and a club.

if (response.success) {
            var footballers = response.footballers;
                for(var i = 0;  i < footballers.length;  i++){

                var listItem =
                '<div class="footballer-card">' +
                '<div class="row">' +
                '<div class="col-md-3">' +
                '<img src=" '+ footballers[i].imageUrl +' " class="footballer-img">' +
                '</div>' +
                '<div class="col-md-8">' +
                '<p class="footballer-details">' +
                '<p class="name"><b>Name: </b>'+ footballers[i].name +'<p/>' +
                '<p class="club"><b>Club: </b>'+ footballers[i].club +'<p/>' +
                '</p>'
                '</div>' +
                '</div>' +
                '</div>'
                ;
                main.append(listItem);
            }

        }

This is how our final app.js file looks like:


$(document).ready(function(){
   //Logic goes here
   var main = $("#main");

   $.ajax({
    url: 'http://pure-forest-79660.herokuapp.com/footballers',
    type: "GET",
    dataType: 'JSON',
    success: function(response){
        if (response.success) {
            var footballers = response.footballers;
            for(var i = 0; i < footballers.length; i++){

                var listItem =
                '<div class="footballer-card">' +
                '<div class="row">' +
                '<div class="col-md-3">' +
                '<img src=" '+ footballers[i].imageUrl +' " class="footballer-img">' +
                '</div>' +
                '<div class="col-md-8">' +
                '<p class="footballer-details">' +
                '<p class="name"><b>Name: </b>'+ footballers[i].name +'<p/>' +
                '<p class="club"><b>Club: </b>'+ footballers[i].club +'<p/>' +
                '</p>'
                '</div>' +
                '</div>' +
                '</div>'
                ;
                main.append(listItem);
            }

        }
        else{
            alert("Oops, an error occured fetching the remote data.");
        }
    }
   });
});

Now, refresh your browser and see the results.

Conclusion

jQuery is a very powerful JavaScript library that allows us to easily perform tasks that would have been a little difficult and tiresome using plain JavaScript. We just found out how incredibly easy it is to make GET request with it by using it's ajax function and providing the url, method type, dataType and the success function. I really hope you enjoyed reading and practicing with this tutorial. If there is any important thing I left out, kindly let me know in the comments section.

Happy JQuery' ing!

:)

Kwabena Berko

1 post

Full Stack Javascript Developer, UI/UX Enthusiast