Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

How to Use jQuery Post Method to Call OpenWeatherMap API?

3.86/5 (9 votes)
20 Oct 2018CPOL2 min read 25.7K   283  
In this tutorial, I will show how to make API calls with jQuery Post Method which is an AJAX method of jQuery.

Introduction

With jQuery Post method, you can make calls to any API and Web Service easily. In this tutorial, I will teach you how to make an API call using this method.

I chose the OpenWeatherMap API to illustrate the codes to you. To tell you more about the OpenWeatherMapAPIIt is a very popular and a free weather API, that provides weather information for all the cities on earth.

Image 1

Background

Before making the API call, you should create your free account at OpenWeatherMap and get your API Key. You will use this API Key to make the calls.

OpenWeatherMap API URL

Typically, we make the API call to this URL: 

http://api.openweathermap.org/data/2.5/weather?id=CITYIDappid=APIKEY&units=metric

Here, we pass the CITYID and the APIKEY to this URL.

OpenWeatherMap JSON

The API returns the response in a JSON format. This JSON contains the weather information of the city. The OpenWeatherMap JSON looks like:

JavaScript
{
"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds",
"description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,
"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200
}

Page HTML

MyHTML page contains 5 radio buttons for 5 citiesMelbourne, Auckland, New Delhi, Abu Dhabi and Lahore.

There is a button, which on clicking, will call the OpenWeatherMap API with jQuery .post() method. Finally, the weather of the city is shown in the div element.

The below 2 images show the weather report of 2 major cities of this planet:

Abu Dhabi Weather Report

abu dhabi weather report

Melbourne Weather Report

melbourne weather report

This is the HTML of my page:

ASP.NET
<div class="container">
    <div id="apiDiv">
        <h4>Select the City for Weather Report</h4>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="7839805">Melbourne</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="2193734">Auckland</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="1261481">New Delhi</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="292968">Abu Dhabi</span>
        <span><input type="radio" id="cityRadio" 
        name="cityRadio" value="1172451">Lahore</span>
        <button id="submit">Submit</button>
        <div class="textAlignCenter">
            <img src="loading.gif" />
        </div>
        <div id="message"></div>
    </div>
</div>

Note: I will show the loading image (a .gif image) during AJAX calls.

Page CSS

Add the below CSS to make the HTML page look appealing:

CSS
<style>
    body {
        background: #111 no-repeat;
        background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111));
    }

    h1, h2, h3 {
        text-align: center;
        color: #FFF;
        margin: 5px 0;
    }

    h1 {
        font-size: 30px;
    }

    h2 a {
        font-size: 25px;
        color: #0184e3;
        text-decoration: none;
    }

    h3 {
        font-size: 23px;
        border-bottom: solid 3px #CCC;
        padding-bottom: 10px;
    }

        h3 a {
            color: #00e8ff;
            text-decoration: none;
        }

            h3 a:hover, h2 a:hover {
                text-decoration: underline;
            }

    .container {
        width: 800px;
        margin: auto;
        color: #FFF;
        font-size: 25px;
    }

        .container #content {
            border: dashed 2px #CCC;
            padding: 10px;
        }

    #reset {
        padding: 5px 10px;
        background: #4CAF50;
        border: none;
        color: #FFF;
        cursor: pointer;
    }

        #reset:hover {
            color: #4CAF50;
            background: #FFF;
        }

#apiDiv {
    padding-left: 20px;
}

    #apiDiv select, #apiDiv button {
        font-size: 25px;
    }

    #apiDiv h4 {
        margin: 10px 0;
    }

        #apiDiv .textAlignCenter {
            text-align: center;
        }

            #apiDiv .textAlignCenter img {
                display: none;
                width: 100px;
            }

        #apiDiv #message table {
            width: 100%;
            border: double 1px #00ffff;
            background: #ff6a00;
        }

            #apiDiv #message table th {
                text-align: left;
                background: #4CAF50;
            }
</style>

Adding the jQuery Reference

Place the jQuery reference just below the ending body tag:

JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>

The jQuery Code

This jQuery code is the brain here, and communicates with the API to fetch the weather of the city. Add it just below where you refer the jQuery.

JavaScript
<script>
    $(document).ready(function () {
        $("input[id='cityRadio']").change(function () {
            $(this).parents("#apiDiv").find
            ("span").css("background", "none");
            $(this).parent().css("background", "#4CAF50");
        });

        $("#submit").click(function (e) {
            var validate = Validate();
            $("#message").html(validate);
            if (validate.length == 0) {
                $.post("http://api.openweathermap.org/data/2.5/weather?id=" + 
                $("input[id='cityRadio']:checked").val() + 
                "&appid=API-KEY&units=metric",
                function (result, status, xhr) {
                    var table = $("<table><tr>
                    <th>Weather Description</th></tr>");

                    table.append("<tr><td>City:</td>
                    <td>" + result["name"] + "</td></tr>");
                    table.append("<tr><td>Country:</td>
                    <td>" + result["sys"]["country"] + 
                    "</td></tr>");
                    table.append("<tr><td>Wind:</td>
                    <td>" + result["wind"]["speed"] + 
                    "Km/h</td></tr>");
                    table.append("<tr><td>Current Temperature:</td>
                    <td>" + result["main"]["temp"] + 
                    " °C</td></tr>");
                    table.append("<tr><td>Humidity:</td><td>" + 
                    result["main"]["humidity"] + "</td></tr>");
                    table.append("<tr><td>Weather:</td><td>" + 
                    result["weather"][0]["description"] + 
                    "</td></tr>");

                    $("#message").html(table);
                }
                ).fail(function (xhr, status, error) {
                    alert("Result: " + status + " " + error + " " + 
                    xhr.status + " " + xhr.statusText);
                });
            }
        });

        $(document).ajaxStart(function () {
            $("img").show();
        });

        $(document).ajaxStop(function () {
            $("img").hide();
        });

        function Validate() {
            var errorMessage = "";
            if ($("input[id='cityRadio']").is(":checked") == false) {
                errorMessage += "? Select City";
            }
            return errorMessage;
        }
    });
</script>

Explanation: In the button click event, first I validate the radio button, so that the user is forced to select a radio button, before clicking the button. The Validate() function does that job for me.

Then I call the API using jQuery .post() method. I passed the City Id and API Key to the API URL.

You can check the API URL in the code where I have given:

JavaScript
$("input[id='cityRadio']:checked").val()

This code provides the value of the radio button which is checked, i.e., the City Id in our case.

The success function of the jQuery Post method gets the weather of the city in JSON format. I extracted the city weather details from this JSON and show it in the HTML table form.

In the change event of the radio button:

JavaScript
$("input[id='cityRadio']").change(function () { });

I am providing the background color to the currently checked radio button.

I created the same application in ASP.NET MVC. Do check this article too - OpenWeatherMap API in ASP.NET MVC. 

Conclusion

I hope you enjoyed this tutorial. Please let me know if you have any questions in your mind. Also, do follow me and get updated when I publish new web development tutorials. 

Thank you for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)