Click here to Skip to main content
13,769,337 members
Click here to Skip to main content
Add your own
alternative version

Stats

14.4K views
210 downloads
15 bookmarked
Posted 28 Feb 2017
Licenced CPOL

How to Use jQuery Post Method to Call OpenWeatherMap API?

, 20 Oct 2018
Rate this:
Please Sign up or sign in to vote.
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.

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:

{
"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:

<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:

<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:

<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.

<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:

$("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:

$("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)

Share

About the Author

Yogi S.
Software Developer (Senior)
United States United States
Programming is Fun.
I am a Senior Software Developer working in ASP.NET, MVC, C#, jQuery, HTML, Razor and more. I also write programming based tutorials in my own website, codeproject, dzone and few more. Please connect with my social accounts.

My favorite area is jQuery. Visit my website for jQuery Tutorials in basically every topics (beginners to advanced programmers)
Thanks !

You may also be interested in...

Pro

Comments and Discussions

 
QuestionNice work! Pin
Matias Lopez23-Oct-18 5:34
memberMatias Lopez23-Oct-18 5:34 
QuestionWhy using query string ? Pin
Sara Khan Kulkarni10-Jun-17 5:28
memberSara Khan Kulkarni10-Jun-17 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.181117.1 | Last Updated 20 Oct 2018
Article Copyright 2017 by Yogi S.
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid