Thursday, April 18, 2013

Consuming a web service using jQuery

It looks deceivingly simple. However, you can stuff a lot of specifics in this umbrella parameter options, such as the required ones: url of the web service (url), request content type (contentType), response data type (dataType), callback function for success (success); and the optional ones: callback function in case of failure (error), a timeout for the AJAX request in milliseconds (timeout), etc.

For example, we can call a specific web method in a web service as such.
JQuery .ajax command:
  $.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});
Two things are worth noting in the above JQuery AJAX call. First, we must specify the contentType’s value as application/json; charset=utf-8, and the dataType as json; second, to make a GET request, we leave the data value as empty.
So put it together, the following code demonstrates how we would use JQuery to call the web service we created above.

Calling a web service using jQuery:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head id="Head1" runat="server">
<title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
 <script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">  
</script> 
  <script type="text/javascript">
      $(document).ready(function() {
         $("#sayHelloButton").click(function(event){
             $.ajax({
                 type: "POST",
                 url: "dummyWebsevice.asmx/HelloToYou",
                 data: "{'name': '" + $('#name').val() + "'}",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function(msg) {
                     AjaxSucceeded(msg);
                 },
                 error: AjaxFailed
             });
         });
     });
          function AjaxSucceeded(result) {
              alert(result.d);
          }
          function AjaxFailed(result) {
              alert(result.status + ' ' + result.statusText);
          } 
  </script> 
</head>
<body>
    <form id="form1" runat="server">
     <h1> Calling ASP.NET AJAX Web Services with jQuery </h1>
     Enter your name:
        <input id="name" />
        <br />
        <input id="sayHelloButton" value="Say Hello"
               type="button"  />
    </form>
</body>
</html>

No comments:

Post a Comment