Introduction
There are several ways to call a web service, they are the following:
- Creating Proxy using add web reference
- Creating Proxy using svcutil.exe
- 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.
- Create Web service
We created a method as in the screen above.
- Returning data in JSON format
- string myJsonString = (new JavaScriptSerializer()).Serialize("Hello World");
- Uncomment a line
We need to uncomment the following line if we are calling from jQuery.
- Running the service
The following screen will be displayed.
- Creating Client
Add a web form (any aspx form) to the solution.
- Add jQuery file to webform
- <script src="Scripts/jquery-1.8.2.js"></script>
- Sample code (you may copy the code and need to change the serviceurl method name and so on)
- <html>
- <head>
- <title></title>
- <script src="Scripts/jquery-1.8.2.js"></script>
- <script type="text/javascript">
-
- $(document).ready(function ()
- {
- $("#BTNSERVICE").click(function (event) {
-
-
- $.ajax({
- url: TestWebJquerySVC.asmx/HelloWorld',
- contentType: "application/json; charset=utf-8",
- type: 'POST',
- dataType: 'json',
-
- success: function (data, textStatus, xhr) {
- alert(data.d);
- },
- error: function (xhr, textStatus, errorThrown) {
- alert('a' + textStatus);
- }
- });
-
- }
- </script>
-
- </head>
- <body>
- <form runat="server">
- <asp:button ID="BTNSERVICE" runat="server" text="BTNSERVICE" />
- SAMPLE Application to test service
- </form>
- </body>
- </html>
- Understanding the code.
- We have created a button on which we have registered a button click.
- We are using $.ajax for calling jQuery.
- We have defined success and error callbacks that will be called during a success response from the service and failure from the service.
- Reading output : we should read data using response.d
- Here the response object is data then reading it using data.d.
Running the code
The following will be the output.
Conclusion
We have created a sample application that calls a web service using jQuery Ajax.