How to create Covid19 Country wise status project using REST API ? - GeeksforGeeks

30 Jul, 2020
Today, All Countries in the world fighting with Coronavirus. Every day, Coronavirus cases rising rapidly. It is important for all to keep track of COVID Cases daily and should try to keep himself/herself safe. We have made small web apps that will tell you a total no of cases, new cases, new death, recovery, etc. to the user. You have to just enter the country name and click on search.
This app also protected from clientside scripting and uses Free Covid19 API. The following is the API Link:https://covid19api.com/
Steps to Run the program: We are showing JavaScript and HTML File in this article. All codes including HTML, CSS, js are at my Github profile. The following is the complete project link:https://github.com/rohitdhonicsk/covid19webapp
Git clone https://github.com/rohitdhonicsk/covid19webapp, to copy the GitHub project file on your computer.Now open Index.html file.Type country name and click search.
Git clone https://github.com/rohitdhonicsk/covid19webapp, to copy the GitHub project file on your computer.
Now open Index.html file.
Type country name and click search.
Project File and Module Required:
You should have three main file index.html (Below the code of index.html file), CSS (it is only required if you want to design, You can download CSS from my GitHub repository project file). And the third most important file is JavaScript file (We have given full code below) that is needed to for fetching COVID data and responding to the user search.You require jQuery which is JavaScript Library. You can put CDN Script on your HTML Code from Jquery Official Website OR using Command below:Note: Make sure you have NODE and NPM installed in the machine, otherwise go to the official website of the node to download and install.Firstly, you have to type the below command in the project directory. It will create a package.json file.npm initNow type the below command to install jQuery.npm install jquery
You should have three main file index.html (Below the code of index.html file), CSS (it is only required if you want to design, You can download CSS from my GitHub repository project file). And the third most important file is JavaScript file (We have given full code below) that is needed to for fetching COVID data and responding to the user search.
You require jQuery which is JavaScript Library. You can put CDN Script on your HTML Code from Jquery Official Website OR using Command below:Note: Make sure you have NODE and NPM installed in the machine, otherwise go to the official website of the node to download and install.Firstly, you have to type the below command in the project directory. It will create a package.json file.npm initNow type the below command to install jQuery.npm install jquery
Note: Make sure you have NODE and NPM installed in the machine, otherwise go to the official website of the node to download and install.
Firstly, you have to type the below command in the project directory. It will create a package.json file.
npm init
Now type the below command to install jQuery.
npm install jquery
Project Directory:
The project will look like this:Home Page:
COVID19 stats search for INDIA country:
Steps To Build the Application:
The first step is to go to API and Copy the link of API to the postman app and visualize the JSON format of data. We are using the summary data of API.Create a form in HTML file with the input field is the country name.Assign Id to heading, form, input, and tag that should be used on JavaScript. Below is the Demo HTML file where class and id used for styling and action call.<h1 class='section-heading'>COVID RESULT</h1><h2 class='section-subheading'>SEARCH COUNTRY NAME</h2>  <div class="section-description">    <p class="section-subheading">  <form id="query-form">    <div>      <label for="ingredients">Country :</label>        <input class="textfield" id="ingredients"           type="text" name="ingredients"          placeholder="e.g.India, chiNA"           onChange="sanitizeInputs()" />    </div>      <div class="button">      <br />      <input class="button" type="button"         value="Reset" id="resetButton"         onClick="this.form.reset();resetResults()" />      <input class="button" type="submit"         value="Search ..." id="searchButton" />    </div>  </form>  </p>    <div class="section-subheading"     id="search-results-heading"></div>  <div class="results-div" id="results"></div></div>Now include your CSS file (its optional).Remember to include the below two thing in HTML code:jQuery CDN linkYour JS fileNow, add the following code in your JS file:// This Code calls function name performSearch()// on clicking submit button of form   $(document).ready(function() {    // Add an event listener (performSearch)   // to the form  $("#query-form").submit(function(event)     { performSearch(event); });});Now create performSearch() Function using the below code:function performSearch(event) {    // Variable to hold request  var request;    // Prevent default posting of form   // put here to work in case of errors  event.preventDefault();    // Abort any pending request  if (request) {      request.abort();  }    // Setup some local variables  var $form = $(this);    // Disable the inputs and buttons   // for the duration of the request.  setFormDisabledProps(true);    // It will show heading searching during the request  $("#search-results-heading").text("Searching ...");  $("#results").text("");    // Send the request to API for data  request = $.ajax({      url:"https://api.covid19api.com/summary",      type: "GET",      // data: { i:, q: $("#contains").val()}  });  // Taking country name from input box that we createdpat=$("#ingredients").val();     // Callback handler for success  request.done(function (response, textStatus, jqXHR) {          // Calling formal search after getting data from api    formatSearchResults(response);  });    // Callback handler for failure  request.fail(function (jqXHR, textStatus, errorThrown) {   $("#search-results-heading").     text("Unable to fetch Covid Data, Try again")   $("#results").text("");  });    // Callback handler that will be called in any case  request.always(function () {        // Reenable the inputs      setFormDisabledProps(false);  });}Creating formatSearchResults function that will give the user desire search result.var pat, flag = 0;function formatSearchResults(jsonResults) {      // Storing Json Data in jsonobject variable    var jsonObject = jsonResults;      $("#search-results-heading").text("Search Results");    var formatedText = "";      jsonObject.Countries.forEach(function (item, index) {          // Matching user search data with api data         if (item.Country.toLowerCase() == pat.toLowerCase()) {            var thumbnail = item.NewConfirmed;              // Printing the result            formatedText += "<div class='dish-ingredients-div'><h3>TotalConfirmed: " +                item.TotalConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewDeaths: " +                item.NewDeaths + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewConfirmed: " +                item.NewConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewRecovered: " +                item.NewRecovered + "<h3></div>";              flag = 1;            return;        }    });      // If result not found    $("#results").html(formatedText);      if (!flag) {        $("#search-results-heading")            .text("Dont Fun With it.Please Enter"            + " Correct Country Name e.g-India");        $("#results").text("");    }}And the last step is to protect data from client side scripting and reset function.function resetResults() {  $("#search-results-heading").text("");  $("#results").text("");  flag=0;}  // This function checks the user input fields// for any unacceptable characters and removes// them if foundfunction sanitizeInputs() {  var str = $("#ingredients").val();  str = str.replace(/[^a-zA-Z 0-9, ]/gim, "");  str = str.trim();  $("#ingredients").val(str);}
The first step is to go to API and Copy the link of API to the postman app and visualize the JSON format of data. We are using the summary data of API.
Create a form in HTML file with the input field is the country name.
Assign Id to heading, form, input, and tag that should be used on JavaScript. Below is the Demo HTML file where class and id used for styling and action call.<h1 class='section-heading'>COVID RESULT</h1><h2 class='section-subheading'>SEARCH COUNTRY NAME</h2>  <div class="section-description">    <p class="section-subheading">  <form id="query-form">    <div>      <label for="ingredients">Country :</label>        <input class="textfield" id="ingredients"           type="text" name="ingredients"          placeholder="e.g.India, chiNA"           onChange="sanitizeInputs()" />    </div>      <div class="button">      <br />      <input class="button" type="button"         value="Reset" id="resetButton"         onClick="this.form.reset();resetResults()" />      <input class="button" type="submit"         value="Search ..." id="searchButton" />    </div>  </form>  </p>    <div class="section-subheading"     id="search-results-heading"></div>  <div class="results-div" id="results"></div></div>
<h1 class='section-heading'>COVID RESULT</h1><h2 class='section-subheading'>SEARCH COUNTRY NAME</h2>  <div class="section-description">    <p class="section-subheading">  <form id="query-form">    <div>      <label for="ingredients">Country :</label>        <input class="textfield" id="ingredients"           type="text" name="ingredients"          placeholder="e.g.India, chiNA"           onChange="sanitizeInputs()" />    </div>      <div class="button">      <br />      <input class="button" type="button"         value="Reset" id="resetButton"         onClick="this.form.reset();resetResults()" />      <input class="button" type="submit"         value="Search ..." id="searchButton" />    </div>  </form>  </p>    <div class="section-subheading"     id="search-results-heading"></div>  <div class="results-div" id="results"></div></div>
Now include your CSS file (its optional).
Remember to include the below two thing in HTML code:jQuery CDN linkYour JS file
jQuery CDN link
Your JS file
Now, add the following code in your JS file:// This Code calls function name performSearch()// on clicking submit button of form   $(document).ready(function() {    // Add an event listener (performSearch)   // to the form  $("#query-form").submit(function(event)     { performSearch(event); });});
// This Code calls function name performSearch()// on clicking submit button of form   $(document).ready(function() {    // Add an event listener (performSearch)   // to the form  $("#query-form").submit(function(event)     { performSearch(event); });});
Now create performSearch() Function using the below code:function performSearch(event) {    // Variable to hold request  var request;    // Prevent default posting of form   // put here to work in case of errors  event.preventDefault();    // Abort any pending request  if (request) {      request.abort();  }    // Setup some local variables  var $form = $(this);    // Disable the inputs and buttons   // for the duration of the request.  setFormDisabledProps(true);    // It will show heading searching during the request  $("#search-results-heading").text("Searching ...");  $("#results").text("");    // Send the request to API for data  request = $.ajax({      url:"https://api.covid19api.com/summary",      type: "GET",      // data: { i:, q: $("#contains").val()}  });  // Taking country name from input box that we createdpat=$("#ingredients").val();     // Callback handler for success  request.done(function (response, textStatus, jqXHR) {          // Calling formal search after getting data from api    formatSearchResults(response);  });    // Callback handler for failure  request.fail(function (jqXHR, textStatus, errorThrown) {   $("#search-results-heading").     text("Unable to fetch Covid Data, Try again")   $("#results").text("");  });    // Callback handler that will be called in any case  request.always(function () {        // Reenable the inputs      setFormDisabledProps(false);  });}
function performSearch(event) {    // Variable to hold request  var request;    // Prevent default posting of form   // put here to work in case of errors  event.preventDefault();    // Abort any pending request  if (request) {      request.abort();  }    // Setup some local variables  var $form = $(this);    // Disable the inputs and buttons   // for the duration of the request.  setFormDisabledProps(true);    // It will show heading searching during the request  $("#search-results-heading").text("Searching ...");  $("#results").text("");    // Send the request to API for data  request = $.ajax({      url:"https://api.covid19api.com/summary",      type: "GET",      // data: { i:, q: $("#contains").val()}  });  // Taking country name from input box that we createdpat=$("#ingredients").val();     // Callback handler for success  request.done(function (response, textStatus, jqXHR) {          // Calling formal search after getting data from api    formatSearchResults(response);  });    // Callback handler for failure  request.fail(function (jqXHR, textStatus, errorThrown) {   $("#search-results-heading").     text("Unable to fetch Covid Data, Try again")   $("#results").text("");  });    // Callback handler that will be called in any case  request.always(function () {        // Reenable the inputs      setFormDisabledProps(false);  });}
Creating formatSearchResults function that will give the user desire search result.var pat, flag = 0;function formatSearchResults(jsonResults) {      // Storing Json Data in jsonobject variable    var jsonObject = jsonResults;      $("#search-results-heading").text("Search Results");    var formatedText = "";      jsonObject.Countries.forEach(function (item, index) {          // Matching user search data with api data         if (item.Country.toLowerCase() == pat.toLowerCase()) {            var thumbnail = item.NewConfirmed;              // Printing the result            formatedText += "<div class='dish-ingredients-div'><h3>TotalConfirmed: " +                item.TotalConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewDeaths: " +                item.NewDeaths + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewConfirmed: " +                item.NewConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewRecovered: " +                item.NewRecovered + "<h3></div>";              flag = 1;            return;        }    });      // If result not found    $("#results").html(formatedText);      if (!flag) {        $("#search-results-heading")            .text("Dont Fun With it.Please Enter"            + " Correct Country Name e.g-India");        $("#results").text("");    }}
var pat, flag = 0;function formatSearchResults(jsonResults) {      // Storing Json Data in jsonobject variable    var jsonObject = jsonResults;      $("#search-results-heading").text("Search Results");    var formatedText = "";      jsonObject.Countries.forEach(function (item, index) {          // Matching user search data with api data         if (item.Country.toLowerCase() == pat.toLowerCase()) {            var thumbnail = item.NewConfirmed;              // Printing the result            formatedText += "<div class='dish-ingredients-div'><h3>TotalConfirmed: " +                item.TotalConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewDeaths: " +                item.NewDeaths + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewConfirmed: " +                item.NewConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewRecovered: " +                item.NewRecovered + "<h3></div>";              flag = 1;            return;        }    });      // If result not found    $("#results").html(formatedText);      if (!flag) {        $("#search-results-heading")            .text("Dont Fun With it.Please Enter"            + " Correct Country Name e.g-India");        $("#results").text("");    }}
And the last step is to protect data from client side scripting and reset function.function resetResults() {  $("#search-results-heading").text("");  $("#results").text("");  flag=0;}  // This function checks the user input fields// for any unacceptable characters and removes// them if foundfunction sanitizeInputs() {  var str = $("#ingredients").val();  str = str.replace(/[^a-zA-Z 0-9, ]/gim, "");  str = str.trim();  $("#ingredients").val(str);}
function resetResults() {  $("#search-results-heading").text("");  $("#results").text("");  flag=0;}  // This function checks the user input fields// for any unacceptable characters and removes// them if foundfunction sanitizeInputs() {  var str = $("#ingredients").val();  str = str.replace(/[^a-zA-Z 0-9, ]/gim, "");  str = str.trim();  $("#ingredients").val(str);}
The Complete Javascript Code:
// This Code call function name performSearch()// on clicking submit button of form $(document).ready(function () {      // Add an event listener (performSearch)    // to the form    $("#query-form").submit(function (event)         { performSearch(event); });});  var pat, flag = 0;function formatSearchResults(jsonResults) {      // Storing Json Data in jsonobject variable    var jsonObject = jsonResults;      $("#search-results-heading").text("Search Results");    var formatedText = "";      jsonObject.Countries.forEach(function (item, index) {          // Matching user search data with api data         if (item.Country.toLowerCase() == pat.toLowerCase()) {            var thumbnail = item.NewConfirmed;            // Printing the result            formatedText += "<div class='dish-ingredients-div'><h3>TotalConfirmed: " +                item.TotalConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewDeaths: " +                item.NewDeaths + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewConfirmed: " +                item.NewConfirmed + "<h3></div>";              formatedText += "<div class='dish-ingredients-div'><h3>NewRecovered: " +                item.NewRecovered + "<h3></div>";              flag = 1;            return;        }    });      $("#results").html(formatedText);      // If result not found    if (!flag) {        $("#search-results-heading")            .text("Dont Fun With it.Please Enter"                + " Correct Country Name e.g-India");        $("#results").text("");    }}  function performSearch(event) {      // Variable to hold request    var request;      // Prevent default posting of form -     // put here to work in case of errors    event.preventDefault();      // Abort any pending request    if (request) {        request.abort();    }      // Setup some local variables    var $form = $(this);      // Disable the inputs and buttons     // for the duration of the request.    setFormDisabledProps(true);      // It will show heading searching    // during the request    $("#search-results-heading")            .text("Searching ...");    $("#results").text("");      // Send the request to API for data    request = $.ajax({        url: "https://api.covid19api.com/summary",        type: "GET",        // data: { i:, q: $("#contains").val() }    });      // Taking country name from input    // box that we created    pat = $("#ingredients").val();      // Callback handler for success    request.done(function (response,         textStatus, jqXHR) {        formatSearchResults(response);    });      // Callback handler for failure    request.fail(function (jqXHR,             textStatus, errorThrown) {          // Calling formal search after         // getting data from api        $("#search-results-heading").text("Sorry We Unable to fetch Covid Data.Try again.");        $("#results").text("");    });      // Callback handler that will be    // called in any case    request.always(function () {          // Reenable the inputs        setFormDisabledProps(false);    });}  // This function clears the search results// and the heading "Search Results"function resetResults() {    $("#search-results-heading").text("");    $("#results").text("");    flag = 0;}  // This function checks the user input// fields for any unacceptable characters// and removes them if foundfunction sanitizeInputs() {    var str = $("#ingredients").val();    str = str.replace(/[^a-zA-Z 0-9, ]/gim, "");    str = str.trim();    $("#ingredients").val(str);}
CSS-Misc
HTML-Misc
Node.js-Misc
CSS
HTML
JavaScript
JQuery
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)