How to present Covid-19 India data with JavaScript and AJAX using Rapid API



Welcome to the world of programming. The skills of a developer must be best utilized when the world is stuck in a crisis and is badly in need of data for taking calculated decisions and to mitigate the risk to come out of the crisis.
In today's world of APIS we need not reinvent the wheel as long as there are providers who can provide authentic data through APIS. Once the authenticity of the data is verified the developer can thus focus on rendering the User Interface and provide a good User Experience.

In this short tutorial you will get an insight on how data can be presented for Covid-19 using a simple API which is available in Rapid API. You can register in RAPID API and view the end points(methods) of  "Covid-19 India Data by ZT"  by clicking on the link https://rapidapi.com/ZermeloTechnologies/api/covid-19-india-data-by-zt               
RapidAPI is the world’s largest API marketplace where over a million developers find and connect to thousands of public APIs. We recommend RapidAPI as one of the best API providers currently available in the market due to very active API providers creating new APIS and a huge developer community consuming those APIS. They also have a descent support team available to resolve tickets if raised.


So lets get into how we render Covid-19 India data into a table by consuming "Covid-19 India Data by ZT" API available in Rapid API. We can create a folder and place all the required files.

Required Files
JavaScript files
1. jquery-3.5.1.min.js - Javascript library that makes HTML document traversal and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
Link for download is https://code.jquery.com/jquery-3.5.1.min.js
2. moment.min.js - JavaScript date library for formatting Last Updated Date value in DD-MMM-YYYY HH:mm:ss format.
 Link for download is https://momentjs.com/downloads/moment.min.js
3. datatables.min.js - provides advanced features to the HTML table. The version used is 1.10.21
Link for download is https://datatables.net/download/builder?dt/dt-1.10.21

CSS files
1. style.css - custom css file for external styles.
2. datatables.min.css - css file to provide style for the datatable.

HTML file
1. Covid-19 India State Data.html - The main html file where data is rendered. You can click on this file once the programming is complete to view the India Statewise Data.

Steps
1. Create a folder "Covid19IndiaStats" in your computer.
2. Create a "Covid-19 India State Data.html" file under the folder "Covid19IndiaStats". Code for this file is provided below.
3. Create a folder "resources" under the folder "Covid19IndiaStats"
4. Create 2 subfolders "js" and "css" under the folder "resources" .
5. Place jquery-3.5.1.min.js, moment.min.js and datatables.min.js under the "js" folder.
6. Place style.css and  datatables.min.css under the "css" folder. Code for style.css is provided below.
7. Click on the API link  https://rapidapi.com/ZermeloTechnologies/api/covid-19-india-data-by-zt    from Rapid API and click on the endpoint "Get India State Wise Data". From the Code Snippets section on right copy the value of  "x-rapidapi-key" . This value must be replaced as the value of  x-rapidapi-key in the ajax call in "Covid-19 India State Data.html" file provided below.
8. Open "Covid-19 India State Data.html" using Chrome browser. You should be able to see state wise Covid-19 India data.

Code for Covid-19 India State Data.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Covid19 Stats</title>
 
<link href="resources/css/style.css" rel="stylesheet" />
<link href="resources/css/datatables.min.css" rel="stylesheet" />
<script src="resources/js/jquery-3.5.1.min.js"></script>
 
<script src="resources/js/datatables.min.js"></script>
<script src="resources/js/moment.min.js"></script>
</head>
<body>
<div class="table-responsive" >  
<table class="display_table_responsiveness cell-border table table-hover"
       id="tblCovidData" width="55%">
 <thead>
 <tr style="background-color:#76528BFF;letter-spacing.3pxcolor:white;">
  <th class="no-sort" colspan="9">COVID-19 INDIA</th>
 </tr>
 <tr style="background-color:#FF9900;letter-spacing.3px;">
  <th width="10%" style="color:black" class="no-sort">State / UT</th>
  <th width="5%" style="color:black" class="no-sort">Total Cases</th>
  <th width="5%" style="color:black" class="no-sort">Active Cases</th>
  <th width="5%" style="color:black" class="no-sort">New Cases</th>
  <th width="5%" style="color:black" class="no-sort">Total Death</th>
  <th width="5%" style="color:black" class="no-sort">New Death</th>
  <th width="5%" style="color:black" class="no-sort">Total Recovered</th>
  <th width="5%" style="color:black" class="no-sort">New Recovered</th>
  <th width="10%" style="color:black" class="no-sort">Last Updated</th>
 </tr>
 </thead>
 <tbody>        
 </tbody> 
</table>
</div> 
</body>
<script type="text/javascript">
window.onload = function() {
 setTimeout(function(){ getData();}, 10);
}
$(document).ready(function() { 
 $(function(){
   $("#tblCovidData").dataTable({
       "dom"'<"top"f>rt<"bottom"lip><"clear">',
       "order": [],
    "columnDefs": [ {
     "targets"'no-sort',
     "orderable"false } ],
       "oLanguage": {
       "sEmptyTable""",
           "sInfoEmpty""",
            "sZeroRecords"""},
        "bPaginate"false,
        "bFilter"false,
        "bInfo"false
   });
      
   });
});
function getData()
{ 
let table = document.getElementById('tblCovidData');
$.ajax
({
 type : 'GET',
  url : "https://covid-19-india-data-by-zt.p.rapidapi.com/GetIndiaStateWiseData",
        headers: {'x-rapidapi-host''covid-19-india-data-by-zt.p.rapidapi.com',
        'x-rapidapi-key''Please replace with your confidential x-rapidapi-key value'},
success : function(resultObj){ if (resultObj && resultObj.statusMsg == "OK") { let jsonArr = resultObj.data; if (jsonArr) { let size = jsonArr.length let rowIndex = 1; for(let dataIndex = 0; dataIndex < size; dataIndex++){ rowIndex++; let row = table.insertRow(rowIndex); //state name let stateName = row.insertCell(0); //total cases let totalCases = row.insertCell(1); //active cases let activeCases = row.insertCell(2); //New Cases let newCases = row.insertCell(3); //Total Death let deaths = row.insertCell(4); // New Death let newDeaths = row.insertCell(5); //Total Recovered let recovered = row.insertCell(6); //New Recovered let newRecovered = row.insertCell(7); //data last updated from source let lastUpdated = row.insertCell(8); stateName.innerHTML = jsonArr[dataIndex].name; totalCases.innerHTML = jsonArr[dataIndex].confirmed; activeCases.innerHTML = jsonArr[dataIndex].active; let newCasesFromResponse = Number(jsonArr[dataIndex].newconfirmed);         //only if new cases are greater than 0 a background color is given.         //if new cases are 0 then the cell is left empty if(newCasesFromResponse > 0) { newCases.innerHTML = "+"+jsonArr[dataIndex].newconfirmed; } deaths.innerHTML = jsonArr[dataIndex].deaths;         //only if new deaths are greater than 0 a background color is given.          //if  new deaths are 0 then the cell is left empty let newDeathsFromResponse = Number(jsonArr[dataIndex].newdeaths); if(newDeathsFromResponse > 0) { newDeaths.innerHTML = "+"+jsonArr[dataIndex].newdeaths; } recovered.innerHTML = jsonArr[dataIndex].recovered;         //only if new recovered is greater than 0 a background color is given.          //if  new recovered is 0 then the cell is left empty let newRecoveredFromResponse = Number(jsonArr[dataIndex].newrecovered); if(newRecoveredFromResponse > 0) { newRecovered.innerHTML = "+"+jsonArr[dataIndex].newrecovered; }         // to convert to DD-MMM-YYYY HH:mm:ss date format.         //moment.js is mandatory to be included for this         let formattedDate = moment(jsonArr[dataIndex].lastupdatedtime,             "YYYY-MM-DD HH:mm:ss").format("DD-MMM-YYYY HH:mm:ss");         lastUpdated.innerHTML = formattedDate; }   } } }, error : function() { } }); } </script> </html>

Code for style.css
body,
html {
  overflow-xhidden;
  padding-right0 !important; }
  
html {
  font-family:Roboto,sans-serif;
  line-height1.15;
  -webkit-text-size-adjust100%;
  -webkit-tap-highlight-colorrgba(0, 0, 0, 0); }
  
body {
  font-size1rem;
  font-weightinitial;
  line-heightnormal;
  -webkit-font-smoothingantialiased; 
  padding0;
  margin0;}
.table {
width100%;
margin-bottom1rem;
color#212529; }
 
.table thead th {
border-top0;
border-bottom-width1px;
font-weight600; }
 
.table th,
.table td {
vertical-alignmiddle;
font-weight500;
line-height1;
white-spacenowrap; }
 
.table-responsive {
  displayblock;
  width100%;
  overflow-xauto;
  -webkit-overflow-scrollingtouch; }
 
.dataTable thead th{
 white-spacenormal !important;
}
.display_table_responsiveness{
 display:inline-table;
}
th {
  border-top1px solid #cdd4e0 !important;
  border-bottom1px solid #cdd4e0 !important;
  border-right1px solid #cdd4e0 !important;
  text-align:center;
}
 
th:first-child {
  border-left1px solid #cdd4e0;
}
table tr:nth-child(even) td{
    background-color#67C8FF;
}
table tr:nth-child(odd) td{
    background-colorwhite;
}
/*# dead cases */
#tblCovidData td:nth-child(6):not(:empty)
{
  background-color:red;
  color:#ffffff;
}
/*# new cases */
#tblCovidData td:nth-child(4):not(:empty)
{
  background-color:#EED202;
  color:black;
}
/*# new recovered */
#tblCovidData td:nth-child(8):not(:empty)
{
  background-color:#00FF00;
  color:black;
}
table td:not(:first-child){text-align:right;}
table.dataTable td.dataTables_empty {
    text-aligncenter;
    border-rightnone !important;
    border-leftnone !important;
}
/*# sourceMappingURL=style.css.map */

You can use the endpoint "Get India Total Counts" from "Covid-19 India Data by ZT" API to display the total active cases, total deaths, total confirmed cases etc.

To help you out we have endpoints that has Covid-19 data of India as a whole, statewise, district wise , historical data, testing data  and zone wise Covid-19 data. Let this journey of programming using "Covid-19 India Data by ZT" API embark by technologically helping citizens and communities to come out of this crisis by presenting historical Covid-19 data, data analysis, forecasting the impacts of the pandemic and using innovative ways to help people to stay away from effected zones and thereby be safe.




Comments

  1. Not displaying the stats as you said. I followed each step correctly....

    ReplyDelete
    Replies
    1. Apologies for the delay in response. In order to identify why you have not got the output we have debugging options available in the browser. Please put a console.log(resultObj); inside the success function. You can press F12 key and select the console tab in the browser to identify if there are any errors. Please let us know if you have got the ajax response successfully. You can also mail us to support@zermelotech.com for immediate responses. We will be happy to assist you.
      Regards,
      Zermelo Technologies Support Team.

      Delete

Post a Comment

Popular posts from this blog

Where data is the king

Think twice before you sync