JAVASCRIPT FETCH API EXAMPLE – BUILD A RANDOM USER GENERATOR APP

JAVASCRIPT FETCH API EXAMPLE – BUILD A RANDOM USER GENERATOR APP

 

Welcome folks I am back with another blog post. In this post we will be building a random user generator application with Javascript Fetch API and JQuery. For the application we will be using the random user generator API. So let’s get started with the application.

 

So first of all you should visit the random user generator website and read the docs and get familiar with the api so that you can better understand the application we will be building.

 

 

 

After understanding the API. Create a new directory and open it in Visual Studio Code editor. You can use any code editor it’s totally up to you. Create index.html file and write the general boilerplate code. For styling purposes we will be using bootstrap. So just include the bootstrap CDN for only styling purposes. We will be also be using JQuery so just include CDN for that also. Just write this code in index.html file to start the process.

 

<!DOCTYPE html>
<html>
  <head>
    <title>Javascript Fetch Api Example</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css"/>
  </head>
  <body>
     <div class="container">

     </div>

   </body>
  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="script.js"></script>
</html>

 

As you can see in the code we have included the bootstrap.min.css file and also custom style.css file. And also we have included JQuery and custom script file. So we have setup the boilerplate code of index.html file.

 

Now add a Jumbotron to the application with a certain header and also three radio buttons in order to select the gender of the people. Copy paste the code inside the body of the index.html page.

 

<div style="background-color:blue;color:white;" class="jumbotron">
          <h1>Random User Generator Application</h1> 
        </div>
        <div class="radio">
          <label><input type="radio" value="male" name="gender" checked>Male</label>
        </div>
        <div class="radio">
          <label><input type="radio" value="female" name="gender">Female</label>
        </div>
        <div class="radio">
          <label><input type="radio" value="all" name="gender">All</label>
        </div>

 

 

Add also a select box to select the nationality of the person to return for you. For this we will be using the select input in Bootstrap. Add the code written below.

 

<span>
            <label for="sel1">Select Nationality:</label>
            <select class="form-control" id="nationality">
              <option>AU</option>
              <option>BR</option>
              <option>CA</option>
              <option>CH</option>
              <option>DE</option>
              <option>DK</option>
              <option>ES</option>
              <option>FI</option>
              <option>FR</option>
              <option>GB</option>
              <option>IR</option>
              <option>IE</option>
              <option>NO</option>
              <option>NL</option>
              <option>NZ</option>
              <option>TR</option>
              <option>US</option>
            </select>
        </span>

 

 

This is the end of the front end of the application. Go to the script.js file and we will writing the main business logic of the application. First of all we will making requests to this endpoint https://randomuser.me/api/. So this returns a json response that we will be parsing in our application. In order to return a certain number of results we will be providing a result parameter with a certain value and that will return exact number of results for us. You can read the docs for that.

 

$(document).ready(function(){

var url = "https://randomuser.me/api/?results=10";
var p ="";
var radioValue;
var selectedNationality;
var loadMore;

});

 

 

 

In script.js we have declared some variables and after that you can see the json response which is returned from the api. I am using a free tool called PostMan to analyze this api. You can use this tool to analyze any api. As you can see in the response we have different information such as first and last name, email and profile picture. All this information we will be displaying in the browser. To do that we have to first of all parse the response.

 

fetch(url)
        .then((response) => response.json())
        .then(function(data){
           url = "https://randomuser.me/api/?results=10&nat=AU&gender=male";
           fetchInformation(url);
        })

 

As you can see the code we have used the fetch function to make requests to the api. It takes a given url and we have used some parameters also such as gender,nat,and results. Gender parameter represents the gender of the person, nat represents the country of the application and results represents how many person should the api return to the user. When I open the application for the first time then this function will execute and 10 results will be returned of gender male of nationality AU.

 

$("input[type='radio']").click(function(){
        radioValue = $("input[name='gender']:checked").val();
        selectedNationality = $('#nationality :selected').text();
        $("#result").empty();
        url = "https://randomuser.me/api/?results=10&gender="+radioValue+"&nat=" + selectedNationality;
        if(radioValue){
            fetchInformation(url);
        }
    });

 

 

This is the code required when we select a certain radio button then what code we want to execute. That’s how we select elements using JQuery first of all we are checking if certain radio button is selected then we are getting the text attached to the selected radio button and then we are again making the requests to the api with the selected data.

 

$('#nationality').on('change', function() {
        var p = "";
        $("#result").empty();
        selectedNationality = $('#nationality :selected').text();
        url = "https://randomuser.me/api/?results=10&gender="+radioValue+"&nat=" + selectedNationality;
        fetchInformation(url);
    });

 

This is the code required when we select the data from the select input box to select the nationality of the person. This is the way by which JQuery handles select input i.e what users selects and accordingly we make requests to the api with the selected nationality.

 

function fetchInformation(url){
        fetch(url)
        .then((response) => response.json())
        .then(function(data){

           data.results.forEach(person => {

               p = `<div class="well">
               <img src="${person.picture.medium}" class="img-rounded" alt="Cinque Terre">
               <span style="margin-left:25px;">${person.name.title}  ${person.name.first} ${person.name.last}</span>
               <span>(${person.nat})</span>
               <span style="margin-left:350px;">Email: ${person.email}</span>
               </div>`;
               console.log(p);
               $("#result").append(p);
               
           }); 

          loadMore = '<button id="loadmore" class="btn btn-primary">Load More</button>';

          $("#result").append(loadMore);

          $('#loadmore').on('click', function() {
            fetchInformation(url);
            $(this).remove();
          });
        
           
        })
    }

 

This is the code of the main function i.e. fetchInformation. In this function we are first of all looping through the results array which is there in the JSON. And for editing the data we are using the bootstrap classes to present the data in a nice way. We are using a well class inside it we are using an image and also text for first and last name. And email is also displayed.

 

 

 

You can see the list of users displayed in a nice manner in the form of wells. Each well contains a image view with some borders and also two text which is first and last name. Also email is also displayed side by side. The last feature which remains is that when we press some button then automatically 10 more users come in the list. This functionality we will be adding below. Just copy paste the code.

 

loadMore = '<button id="loadmore" class="btn btn-primary">Load More</button>';

          $("#result").append(loadMore);

          $('#loadmore').on('click', function() {
            fetchInformation(url);
            $(this).remove();
          });

 

 

You can see in the gif animation as we hit the load more button some more users load into the webpage automatically. This completes the whole application. I hope you enjoyed this application very much. Thanks for reading this post and all the source code related to this post is given below. I will be back with another blog post. Until then Thank you very much.

 

Leave a Reply

Close Menu