Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Calling live json web service using jquery ajax

Suggested Videos
Part 68 - How to call wcf service using jquery
Part 69 - Difference between window height and document height
Part 70 - Load data on page scroll using jquery



In this video we will discuss how to call a live weather web service that returns JSON data using jquery ajax.



For the purpose of this demo, we will be using the live weather web service that returns JSON data. The web service can be found at the following URL.
http://openweathermap.org/current

We want to retrieve weather data from the web service and display it on a web page as shown below.

1

Here is the HTML and jQuery code used in the demo

<html>
<head>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnGetWeather').click(function () {
                var resultElement = $('#resultDiv');

                var requestData = $('#txtCity').val() + ',' + $('#txtCountry').val();
                $.ajax({
                    url: 'http://api.openweathermap.org/data/2.5/weather',
                    method: 'get',
                    data: { q: requestData },
                    dataType: 'json',
                    success: function (response) {
                        if (response.message != null) {
                            resultElement.html(response.message);
                        }
                        else {
                            resultElement.html('Weather: ' + response.weather[0].main + '<br/>'
                                + 'Description: ' + response.weather[0].description);
                        }
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
        });
    </script>
</head>
<body style="font-family:Arial">
    <table>
        <tr>
            <td>City</td>
            <td><input type="text" id="txtCity" /></td>
        </tr>
        <tr>
            <td>Country</td>
            <td><input type="text" id="txtCountry" /></td>
        </tr>
    </table>
    <input type="button" id="btnGetWeather" value="Get Weather Data">
    <br /><br />
    <div id="resultDiv">
    </div>
</body>
</html>

jQuery tutorial for beginners

1 comment:

  1. Hi. I was watiching your video in youtube, I tried to replicated the example in my computer, but I recived a message error from ajax and don't work. Could you give me any idea for try to fix my code. thanks.

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.