Saturday, April 7, 2012

Jquery Ajax Working Example (call a webservice using Jquery AJAX)

In this example I will show you how to call the webservice
using jquery ajax.

The return from this webservice is a json resultset that has the structure shown in the image below

To make this call just copy paste the text below into notepad and save it with a .html extension

    <title>Ajax webservice example</title>
    <script src="" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            //This means when the button btnWebserviceCaller is clicked the call the function CallWebService

            //This code means when user presses enter in the text box txtSearch then click the button btnWebserviceCaller
            $("#txtSearch").keyup(function (event) {
                if (event.keyCode == 13) {

            function CallWebService() {

                $("#divResults").text("Please Wait...");
                var searchTerm = $("#txtSearch").val();
                var webMethod = "" + searchTerm;

                //This is where the ajax call is made
                    type: "GET",
                    url: webMethod,
                    contentType: "application/x-www-form-urlencoded", //this is format to sent to the server
                    dataType: "jsonp", //format to expect back from the server
                    success: function (msg) {
                        //if success, come in here
                        var dislplayHtml = "<br/>";

                        $.each(msg.results, function () {
                            //come in here for every result in the array msg.results
                            $.each(this, function (key, value) {
                                //come in here for every key value pair with in a result
                                dislplayHtml = dislplayHtml + key + ":" + value + "<br/>";
                            dislplayHtml = dislplayHtml + "<br/><br/>";


                    }, //success function ends here
                    error: function (xhr, msg) {//if fail, come in here
                    } //error function ends here
                }); //ajax function ends here

            } //function  CallWebService ends here

    Enter Search Term:
    <input type="text" id="txtSearch" value="Metallica" />
    <button id="btnWebserviceCaller" type="button">
        Search Itunes</button>
    <br />
    <div id="divResults">

Note: If you are making jquery ajax call to an external domain, the only call you can make is a GET call with  dataType: "jsonp". POST calls are possible only if you are making a call within the domain in which your ajax page is hosted. This is a security restriction enforced by the browser.

Check this out for more info on jquery ajax.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator