Using jQuery to display COVID-19 statistics

Loading

Using jQuery to Display COVID-19 Statistics – A Complete Guide

Table of Contents

1️⃣ Introduction to COVID-19 Data APIs
2️⃣ Setting Up jQuery in Your Project
3️⃣ Understanding the COVID-19 API
4️⃣ Writing jQuery AJAX Code to Fetch Data
5️⃣ Handling API Responses and Displaying Data
6️⃣ Enhancing the User Experience
7️⃣ Error Handling and Debugging
8️⃣ Security Considerations
9️⃣ Additional Features and Improvements
🔟 Conclusion


1️⃣ Introduction to COVID-19 Data APIs

In this guide, we will build a real-time COVID-19 statistics dashboard using jQuery and AJAX. By fetching data from a publicly available API, we can dynamically display the latest COVID-19 cases, recoveries, and deaths.

Why use jQuery?
✔ Simplifies AJAX calls
✔ Cross-browser compatibility
✔ Easy DOM manipulation
✔ Lightweight and efficient


2️⃣ Setting Up jQuery in Your Project

To start, create an HTML file and include jQuery.

Adding jQuery (CDN Method)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>COVID-19 Statistics</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>COVID-19 Statistics</h1>
    <button id="fetch-data">Get Latest Stats</button>
    <div id="covid-data"></div>
</body>
</html>

Alternatively, you can download jQuery from jQuery.com and include it locally:

<script src="jquery-3.6.0.min.js"></script>

3️⃣ Understanding the COVID-19 API

We will use disease.sh API, a free API for global COVID-19 data.

Base URL:

https://disease.sh/v3/covid-19/

🔹 Global Stats:

https://disease.sh/v3/covid-19/all

🔹 Country-Specific Stats:

https://disease.sh/v3/covid-19/countries/{COUNTRY_NAME}

Example API Response

{
    "cases": 500000,
    "deaths": 12000,
    "recovered": 450000,
    "updated": 1710000000000
}

4️⃣ Writing jQuery AJAX Code to Fetch Data

We will use jQuery’s AJAX method to fetch COVID-19 data when the user clicks the “Get Latest Stats” button.

Basic AJAX Call to Fetch Global Data

$(document).ready(function() {
    $("#fetch-data").click(function() {
        $.ajax({
            url: "https://disease.sh/v3/covid-19/all",
            method: "GET",
            success: function(response) {
                $("#covid-data").html(`
                    <p>Total Cases: ${response.cases}</p>
                    <p>Total Deaths: ${response.deaths}</p>
                    <p>Total Recovered: ${response.recovered}</p>
                `);
            },
            error: function(error) {
                $("#covid-data").html("<p>Error fetching data. Please try again.</p>");
            }
        });
    });
});

How It Works:

  1. When the user clicks the “Get Latest Stats” button, an AJAX call is made.
  2. The success function displays the COVID-19 data.
  3. The error function handles API errors.

5️⃣ Handling API Responses and Displaying Data

Now, let’s improve the UI to make data more readable.

Improved HTML with Styling

<!DOCTYPE html>
<html lang="en">
<head>
    <title>COVID-19 Statistics</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f4f4f4;
        }
        #covid-data {
            margin-top: 20px;
            padding: 20px;
            background: white;
            display: inline-block;
            border-radius: 10px;
        }
        .stats {
            font-size: 20px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>COVID-19 Live Statistics</h1>
    <button id="fetch-data">Get Latest Stats</button>
    <div id="covid-data">
        <p>Click the button to load data.</p>
    </div>

    <script>
        $(document).ready(function() {
            $("#fetch-data").click(function() {
                $("#covid-data").html("<p>Loading...</p>");
                $.ajax({
                    url: "https://disease.sh/v3/covid-19/all",
                    method: "GET",
                    success: function(response) {
                        $("#covid-data").html(`
                            <p class="stats">🌍 Total Cases: <b>${response.cases.toLocaleString()}</b></p>
                            <p class="stats">💀 Total Deaths: <b>${response.deaths.toLocaleString()}</b></p>
                            <p class="stats">💪 Total Recovered: <b>${response.recovered.toLocaleString()}</b></p>
                        `);
                    },
                    error: function() {
                        $("#covid-data").html("<p>Error fetching data. Please try again.</p>");
                    }
                });
            });
        });
    </script>
</body>
</html>

Enhancements:

  • Added loading text while fetching data
  • Formatted numbers with .toLocaleString()
  • Styled data for better readability

6️⃣ Enhancing User Experience

📌 Adding Country-Specific COVID Data

Modify the HTML to include an input field:

<input type="text" id="country-input" placeholder="Enter country (e.g., India)">
<button id="fetch-country-data">Get Country Stats</button>

Modify the AJAX call:

$("#fetch-country-data").click(function() {
    var country = $("#country-input").val();
    
    if (country === "") {
        alert("Please enter a country.");
        return;
    }

    $("#covid-data").html("<p>Loading...</p>");

    $.ajax({
        url: `https://disease.sh/v3/covid-19/countries/${country}`,
        method: "GET",
        success: function(response) {
            $("#covid-data").html(`
                <p class="stats">🌍 Country: <b>${response.country}</b></p>
                <p class="stats">😷 Total Cases: <b>${response.cases.toLocaleString()}</b></p>
                <p class="stats">💀 Total Deaths: <b>${response.deaths.toLocaleString()}</b></p>
                <p class="stats">💪 Total Recovered: <b>${response.recovered.toLocaleString()}</b></p>
            `);
        },
        error: function() {
            $("#covid-data").html("<p>Error fetching data. Try again.</p>");
        }
    });
});

New Features:

  • Allows users to enter a country name
  • Fetches and displays COVID-19 statistics for that country
  • Displays an error message if no country is entered

7️⃣ Error Handling and Debugging

Handling Invalid Country Inputs

error: function(xhr) {
    if (xhr.status === 404) {
        $("#covid-data").html("<p>Country not found. Please enter a valid country.</p>");
    } else {
        $("#covid-data").html("<p>Error fetching data. Try again.</p>");
    }
}

8️⃣ Security Considerations

🔹 Use HTTPS API URLs to prevent man-in-the-middle attacks
🔹 Avoid hardcoding API keys in the frontend
🔹 Implement rate limiting to prevent excessive API calls


9️⃣ Additional Features

Add Graphs using Chart.js
Store previous searches in localStorage
Create a COVID-19 news section


🎯 We built a real-time COVID-19 statistics dashboard using jQuery and AJAX. The project dynamically fetches global and country-specific COVID-19 stats.

Would you like me to add a chart or map to visualize the data? Let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *