Calling WCF Without Creating Proxy Using jQuery Ajax


There are several ways to call a web service, they are the following:

  1. Creating Proxy using add web reference
  2. Creating Proxy using svcutil.exe
  3. Calling the web service using AJAX jQuery

Here we will learn how to call a webservice/WCF using jQuery Ajax.

The following is the procedure.

  1. Create Web service

    Create Web service

    We created a method as in the screen above.

  2. Returning data in JSON format
    1. string myJsonString = (new JavaScriptSerializer()).Serialize("Hello World");  
  3. Uncomment a line

    We need to uncomment the following line if we are calling from jQuery.

  4. Running the service

    The following screen will be displayed.

    Running the service

  5. Creating Client

    Add a web form (any aspx form) to the solution.

  6. Add jQuery file to webform
    1. <script src="Scripts/jquery-1.8.2.js"></script>  
  7. Sample code (you may copy the code and need to change the serviceurl method name and so on)
    1. <html>  
    2.         <head>  
    3.             <title></title>  
    4.           <script src="Scripts/jquery-1.8.2.js"></script>  
    5.         <script type="text/javascript">  
    7.             $(document).ready(function ()  
    8.             {  
    9.                 $("#BTNSERVICE").click(function (event) {  
    12. $.ajax({  
    13.                     url: TestWebJquerySVC.asmx/HelloWorld',  
    14.                     contentType: "application/json; charset=utf-8",  
    15.                     type: 'POST',  
    16.                     dataType: 'json',  
    18.                     success: function (data, textStatus, xhr) {  
    19.                         alert(data.d);  
    20.                     },  
    21.                     error: function (xhr, textStatus, errorThrown) {  
    22.                         alert('a' + textStatus);  
    23.                     }  
    24.                 });  
    26.                     }  
    27.      </script>  
    29.     </head>  
    30.     <body>   
    31.            <form runat="server">  
    32.           <asp:button ID="BTNSERVICE" runat="server"  text="BTNSERVICE" />  
    33.                SAMPLE Application to test service  
    34.          </form>  
    35.     </body>  
    36.      </html>  
  8. Understanding the code.

    1. We have created a button on which we have registered a button click.

    2. We are using $.ajax for calling jQuery.

    3. We have defined success and error callbacks that will be called during a success response from the service and failure from the service.

    4. Reading output : we should read data using response.d

    5. Here the response object is data then reading it using data.d.

Running the code

The following will be the output.

hello word


We have created a sample application that calls a web service using jQuery Ajax.