Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

January 7, 2014

Consume Web Service using jQuery

jQuery is a javascript library than can be used to call web services among many other functions. In this example, I will create a web service using asmx and use jQuery to pass and retrieve data from the web service using json. This is really useful as this means we can consume the web service from any platform like jsp, php and not only from I have used json for transmitting data and it is in a platform independent technology that transmits data in an "attribute : value" format.

For this example, I will start with the web service. It's going to be asmx service that simply adds and subtracts numbers that it retrieves from the front end. Here's the code for the web service.

web service
  1. using System.Web.Services;
  3. namespace WebApplication1
  4. {
  5.     [WebService(Namespace = "")]
  6.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  7.     [System.ComponentModel.ToolboxItem(false)]
  8.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
  9.     [System.Web.Script.Services.ScriptService]
  10.     public class WSPrac : System.Web.Services.WebService
  11.     {
  12.         [WebMethod]
  13.         public double Add(double a, double b)
  14.         {
  15.             return a + b;
  16.         }
  18.         [WebMethod]
  19.         public double Substract(double a, double b)
  20.         {
  21.             return a - b;
  22.         }
  23.     }
  24. }

The code self explanatory. The important bit to note is that the line "[System.Web.Script.Services.ScriptService]" needs to be uncommented. This will allow the service to be called using javascript.

On the front end, I have couple of text fields, 1 option field to select to add or to subtract, a button that will trigger the script when clicked and a span element that will display the data. Here's the code for the html front end.

html front end
  1. <body>
  2.     <input type="text" id="t1" />
  4.     <select id="sel">
  5.         <option value="Substract">Substract</option>
  6.                 <option value="Add">Add</option>
  7.     </select>
  9.     <input type="text" id="t2" />
  10.     <input type="button" id="b2" value="Calc" /><br />
  11.     <span id="span1"></span>
  12. </body>

In the last bit is the javascript section. Here's the code for this.

jQuery block
  1. <script type="text/javascript" src=""></script>
  2.        <script type="text/javascript">
  4.     $(document).ready(function () {            
  5.         $('#b2').click(function () {
  6.             var url = "WSPrac.asmx/" + $('#sel').val();
  7.             $.ajax({
  8.                 type: "POST",
  9.                 contentType: "application/json; charset=utf-8",
  10.                 url: url,
  11.                 data: "{ a: '" + $('#t1').val() + "',  b: '" + $('#t2').val() + "'}",
  12.                 dataType: "json",
  13.                 success: function (data) {
  14.                     $("#span1").html(data.d);                  
  15.                 },
  16.                 error: function () {
  17.                     $("#span1").html("Error!!!");
  18.                 }                   
  19.         });
  20.     });
  21.     });
  22. </script>

To start with I am calling jquery source file. Next, in the button click handler, I am forming the service url based on the selection. The important bit is this line

  1. data: "{ a: '" + $('#t1').val() + "',  b: '" + $('#t2').val() + "'}"


Note that a and b are parameter names in the service and I am sending the value of the text boxes. Finally, on success, I am populating the data in the span element. In case, error occurs, for example, if we type in "abc" in the text box or the web service is down, then the error function is fired and the text "Error!!!" is displayed within the span element.

Another thing to note is that the return value in json has .d at the end. This is within the success function as below.

  1. success: function (data) {
  2.     $("#span1").html(data.d);                  
  3. }

The .d is a wrapper that ensures the payload is a json object.

Reference: Shahed Kazi at