Consuming a RESTful web service with jQuery and Ajax

In my last post, we created a REST WCF web service using Visual Studio 2010. In this article, we’ll write a client side web applicaiton that uses jQuery and Ajax to consume a REST web service.

First, create an HTML page that includes a reference to a jQuery library, a <div> tag where we’ll display the service output, a button that will fire the Ajax request to the web service and one that will clear the output <div>.


<html>
<head>
<title>Consume a REST Web Service</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"/>
</head>
<body>
<p><div id="myOutput">Output Goes Here</div><p>
<p><input id="myButton" value="Get Artist" type="submit" /></p>
<p><input id="myClearButton" value="Clear Artist" type="submit" /></p>


Next, add the jQuery to run when the Get Artist button is clicked.

<script type="text/javascript">
 $("#myButton").click(function() {
        var artistURL = "http://development.dlwelch.com/examples/restservice/JazzArtists.svc/json/Shirley";
        var returnData = "";
        $.ajax({
            type: "GET",
            dataType: "json",
            async: true,
            url: artistURL,
            error: function(request, status, error) { alert(request.responseText) },
            success: function(data) {
                $("div#myOutput").html(" ");
                returnData = "<table style='font-size:8pt;'><tr><th>Artist</th><th>Grammys</th></tr>";
                for (prop in data) {
                    if (!data.hasOwnProperty(prop)) { continue; }
                    if (data[prop] != null) {
                        for (var i = 0; i < data[prop].length; i++) {
                            returnData += "<tr><td>" + data[prop][i]["FirstName"] 
                                       + " " + data[prop][i]["LastName"] + "</td><td align='right'>" 
                                       + data[prop][i]["Grammy"] + "</td></tr>";
                        }
                    }
                }
                returnData = returnData + "</table>";
                $("div#myOutput").html(returnData);
            }
        });
        return (false);
    });
</script>

...

Code line 3 defines the URI of the resource, in our case, the artist Shirley. Line 6 indicates we are sending an HTTP GET request to the resource and line 7 says we’ll evaluate the response as JSON and send a JavaScript object back to our success function on line 11. Since a JavaScript object was returned, line 14 starts the loop to find the property holding the response data. Line 15 test the current property to see if it’s a built in property of a JavaScript object. If so, skip it. Once we reach the property with our data, we loop through all the artist objects and create our HTML string for the output <div>.

Finally, add the jQuery to clear the output and finish your HTML.

<script type="text/javascript">
 $("#myClearButton").click(function() {
        $("div#myOutput").html("Output Goes Here");
        return (false);
    });

</script>


</body>
</html>


Your page should look like this. Click on the Get Artist button to see it work!



You can see a working example and grab the code for Ajax calls of all four HTTP verbs on my development site in the WCF RESTful Web Service example.

Tagged with: , ,
Posted in JavaScript and jQuery, REST, Web Services
2 comments on “Consuming a RESTful web service with jQuery and Ajax
  1. Albert says:

    Hi Dedra,

    Thanks for the tutorial helped me a lot, but I have a question, how I can do a search from a web service? I have a REST service I have ever consumed, but now I need to do a search on that data, for example:

    I have

    Athlete Test Event

    Rowing athlete 1 World Championship
    Cycling athlete 2 State Championships

    and I want to search only for event How I can do this?

    Thank you!

Advertisement