Example: How to use JQuery AJAX Method to Call an API

Example: How to use JQuery AJAX Method to Call an API

One of the best features of jQuery AJAX Method is to load data from external website by calling APIs, and get the response in JSON or XML formats. In this example I will show you how easy it is to make such API calls in jQuery AJAX.

OpenWeatherMap API

The OpenWeatherMap API provides the complete weather information for any location on Earth including over 200,000 cities. This API provides the response in JSON format.

To make your API call, first create your Free Account in their website and get your API KEY. Then use this KEY to make API calls with jQuery AJAX.

The format of the OpenWeatherMap API URL is:
http://api.openweathermap.org/data/2.5/weather?id=CITYID&appid=API-KEY&units=metric
The JSON returned by the OpenWeatherMap API is:
{
  "coord": {
    "lon": -74.01,
    "lat": 40.71
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": -3.09,
    "pressure": 1023,
    "humidity": 53,
    "temp_min": -6,
    "temp_max": -1
  },
  "visibility": 16093,
  "wind": {
    "speed": 2.1,
    "deg": 320
  },
  "clouds": { "all": 1 },
  "dt": 1486113300,
  "sys": {
    "type": 1,
    "id": 1972,
    "message": 0.083,
    "country": "US",
    "sunrise": 1486123400,
    "sunset": 1486160222
  },
  "id": 5128581,
  "name": "New York",
  "cod": 200
}

API Call with jQuery AJAX Method

In our application there is a HTML Select control and a button. The Select control contains the city names of New York, San Francisco, London, Mumbai & Santa Lucia.

When a user selects any city and presses the button, then the button click event will call the OpenWeatherMap API (using jQuery AJAX Method) and shows the weather information of the city.

jquery ajax OpenWeatherMap api

The Page HTML:

<select id="citySelect">
    <option value="Select">Select</option>
    <option value="5128581">New York</option>
    <option value="5391959">San Francisco</option>
    <option value="2643743">London</option>
    <option value="1275339">Mumbai</option>
    <option value="8199396">Santa Lucia</option>
</select>
<button id="submit">Submit</button>
<div class="textAlignCenter">
    <img src="~/Content/Image/loading.gif" />
</div>
<div id="message"></div>

Note – The loading.gif is a loading image that will be shown during AJAX calls while the message div will show the weather information of the selected city.

CSS to style the HTML elements

<style>
#viewContent {
    padding-left: 20px;
}

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

    #viewContent h4 {
        margin: 10px 0;
    }

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

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

    #viewContent #message table {
        width: 100%;
    }

        #viewContent #message table th {
            text-align: left;
            text-decoration: underline;
        }
</style>

The jQuery Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $("#submit").click(function (e) {
        var validate = Validate();
        $("#message").html(validate);
        if (validate.length == 0) {
            $.ajax({
                type: "POST",
                url: "http://api.openweathermap.org/data/2.5/weather?id=" + $("#citySelect").val() + "&appid=API-KEY&units=metric",
                dataType: "json",
                success: 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>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);
                },
                error: 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 ($("#citySelect").val() == "Select") {
            errorMessage += "► Select City";
        }
        return errorMessage;
    }
});
</script>

Note – On the button click event I first did some validation by telling the user to select a city before they press the button. Then the jQuery AJAX method calls the OpenWeatherMap API by passing the CITY ID and API KEY.

The API returns the city’s weather in JSON format which is converted into a HTML table form and shown inside the message div.

DEMO DOWNLOAD

Conclusion
In this way you can call any API to fetch data from jQuery AJAX method. It is not only very simply but powerful enough to make interactive features in your websites.

Do you have any question? Please ask!

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.