Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » WCF » Consuming WCF / ASMX / REST service using JQuery

Consuming WCF / ASMX / REST service using JQuery

This step by step tutorial demonstrates how to consume WCF, ASMX, and REST service from an application using JQuery.

Page Views : 84003
Downloads : 2820
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
HTTPServiceJquery.zip | HTTPServiceJquery.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


In this article I will explain how to consume a WCF / ASMX service using jQuery.  The scope of the article is limited to creating &  consuming different kind of services using jQuery. I have segregated this article into 7 topics based on the service consumption.

  1. Calling ASMX Web service using jQuery
  2. Calling WCF service using jQuery and retrieving data in JSON Format
  3. Calling WCF service using jQuery and retrieving data in XML Format
  4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)
  5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format
  6. Calling REST based WCF service using jQuery
  7. Streaming an image through WCF and request it through HTTP GET verb..

If you have never heard about jQuery or WCF or JSON, please learn it before dwelling into this article. The scope  is limited to service creation and consumption.

I used
Visual web developer 2008 to develop this sample. Additional tools used: Firebug and HttpAnalyzer

3 project structure.jpg

In the below example I have  used jQuery version 1.3.2 , you can download the same from http://jQuery.com/. This article demonstrates how our jQuery based browser app will retrieve the Provinces for supplied country. All the services are hosted in the same web  application. Please download the source code to experiment the sample by yourself.

1Screen.jpg

For calling the service we need to use the .ajax method of jQuery which makes XMLHttpRequest
to the
server.   In the below code section I have explained the key value pair attributes to be passed  by marking comments on the right side of the attribute.

     <script type="text/javascript" language="javascript" src="script/jQuery-1.3.2.min.js" "></script>

     <script type="text/javascript">

        var varType;
        var varUrl;
        var varData;
        var varContentType;
        var varDataType;
        var varProcessData;

        function CallService()
        {
                $.ajax({
                    type                : varType, //GET or POST or PUT or DELETE verb
                    url                   : varUrl, // Location of the service
                    data                : varData, //Data sent to server
                    contentType    : varContentType, // content type sent to server
                    dataType         : varDataType, //Expected data format from server
                    processdata    : varProcessData, //True or False
                    success            : function(msg) {//On Successfull service call
                    ServiceSucceeded(msg);                    
                    },
                    error: ServiceFailed// When Service call fails
                });
        }
    </script>

 I have made the above method generic to use it for all different type of services which we are going to discuss.

Business Logic:

Business logic for below demonstrated service is quite simple, we store Country and Province details in a Name Value collection ,When a request supplies the country name it returns the provinces associated with it.

public class CountryProvinceBL
{
    NameValueCollection nvProvince = null;
    public CountryProvinceBL()
    {
        nvProvince = new NameValueCollection();
        nvProvince.Add("usa", "Massachusetts");
        nvProvince.Add("usa", "California");
        nvProvince.Add("india", "Tamil Nadu");
        nvProvince.Add("india", "Karnataka");
    }
    
    public string[] GetProvince(string Country)
    {  return nvProvince.GetValues(Country).ToArray();}

}

1. Calling ASMX Web service using jQuery

Step 1:

  Create a web service and add the below code

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Below line allows the web service to be called through HTTP protocol.
[System.Web.Script.Services.ScriptService]
public class CountryProvinceWebService : System.Web.Services.WebService
{

    [WebMethod]
   //Business Logic returns the provinces for the supplied country
    public string[] GetProvince(string Country)
    {  return new CountryProvinceBL().GetProvince(Country); }    
}

Step 2:

Invoke the below method on button click

        function CountryProvinceWebService() {
            varType              = "POST";         
            varUrl                 = "service/CountryProvinceWebService.asmx/GetProvince";
            //Pass country from drop down ddlCountry'
            varData               = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType  = "application/json; charset=utf-8";
            varDataType       = "json";varProcessData = true; CallService();
        }

Step 3:

 On Success  "ServiceSucceeded" will be called and it will populate the provinces dropdown with the values sent by the server.

        function ServiceSucceeded(result) {
            var ProvinceDDL = document.getElementById("ddlProvince");
            for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
            var resultObject = result.d; // Constructed object name will be object.d //Button
            for (i = 0; i < resultObject.length; i++) {
                    var opt = document.createElement("option"); opt.text = resultObject[i];
                    ProvinceDDL.options.add(opt)
                }
        }


2. Calling WCF service using jQuery and retrieving data in JSON Format
   
Step 1:

Define  the Contracts  in the interface ICountryProvinceWCFService

[ServiceContract]
public interface ICountryProvinceWCFService
{
    [OperationContract]
    [WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]    
    string[] GetProvince(string Country);
}

Implement the contract in class CountryProvinceWCFService

public class CountryProvinceWCFService : ICountryProvinceWCFService
{   
  // Call Business Logic to get provinces
    public string[] GetProvince(string Country)
    {return new CountryProvinceBL().GetProvince(Country); }
}

Step 2:   

Define the configuration in web.config

a) <serviceMetadata httpGetEnabled="true" > enables the user to view the metadata through web browser and generate
WSDL  file

b)  setting includeExceptionDetailInFaults = "true" allows the WCF service throw original error , it will be useful while debugging the application.

c) Adding         <webHttp/> to endpoint behaviour  & webHttpBinding  to binding enables the web programming model for WCF and allows the service to be accessible through web protocols.

d) Define contract and  name of the service

Figure 1: Web.config

 <system.serviceModel>
    <behaviors>
        <serviceBehaviors>
           <behavior name="CountryProvinceBehavior">
               <serviceMetadata httpGetEnabled="true" />
               <serviceDebug includeExceptionDetailInFaults="true" />
          </behavior>
       </serviceBehaviors>
       <endpointBehaviors>
           <behavior name="CountryProvinceBehavior">
              <webHttp/>        
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <services>
         <service behaviorConfiguration="CountryProvinceBehavior" name="CountryProvinceWCFService">
                <endpoint address="" binding="webHttpBinding" contract="ICountryProvinceWCFService" behaviorConfiguration="CountryProvinceBehavior"/>     
         </service>
    </services>
</system.serviceModel>


Step 3:

   Invoke the WCF service on the button click event

        function CountryProvinceWCFJSON() {
            varType              = "POST";
            varUrl                 = "service/CountryProvinceWCFService.svc/GetProvince";
            varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType = "application/json; charset=utf-8";
            varDataType      = "json"; varProcessData = true; CallService();
        }


On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.

   function ServiceSucceeded(result) {/
       var ProvinceDDL = document.getElementById("ddlProvince");
       for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
               // Constructed object name will be object.[ServiceName]Result // Button 2 & 3
              var resultObject = result.GetProvinceResult;
           for (i = 0; i < resultObject.length; i++) {
               var opt = document.createElement("option"); opt.text = resultObject[i];
               ProvinceDDL.options.add(opt)
           }       
   }


3. Calling WCF service using jQuery and retrieving data in XML Format


Step 1:

In operation contract set ResponseFormat to XML.
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Xml)]
    string[] GetProvinceXML(string Country);

Then implement the service

    public string[] GetProvinceXML(string Country)
    {  return new CountryProvinceBL().GetProvince(Country); }


    Use the web.config,  defined in  Figure 1 .

Step 2:

 Invoke the WCF service on the button click event, Make sure you set the expected data type as XML
        function CountryProvinceWCFXML() {
            varType              = "POST";
            varUrl                 = "service/CountryProvinceWCFService.svc/GetProvinceXML";
            varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType = "application/json; charset=utf-8";
            varDataType      = "xml";  varProcessData = true; CallService();
        }

Step 3:

On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.

          function ServiceSucceeded(result) {
              var ProvinceDDL = document.getElementById("ddlProvince");
              for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
            //Below jQuery code will loop through the XML result set
              $(result).find("GetProvinceXMLResult").children().each(function() {
                  var opt = document.createElement("option"); opt.text = $(this).text();
                  ProvinceDDL.options.add(opt)
              });          
          }

4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)

In this example Country and Browser type will be passed as input parameter to the WCF service in JSON format, Upon receiving the values the service will send back provinces for the passed country and  some comments for the browser information.

Step 1:

Define Data contract and service contact  for the service

[DataContract]
public class CustomData
{
    [DataMember]
    public String BrowserInfo;
    [DataMember]
    public String[] ProvinceInfo;
}

  [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    CustomData GetProvinceAndBrowser(string Country, string Browser);


And implement the contract in your service call

    public CustomData GetProvinceAndBrowser(string Country, string Browser)
    {
        CustomData customData = new CustomData();
        customData.ProvinceInfo = new CountryProvinceBL().GetProvince(Country);
        if (Browser == "ie")
            customData.BrowserInfo = " Did you learn to program IE 8.0";
        else if (Browser == "firefox")
            customData.BrowserInfo = " Mozilla rocks, try Firebug & Fiddler addon's";
        else
            customData.BrowserInfo = " I did not test in this browser";
        return customData;
    }


Step 2:

   Use the web.config  defined in figure 1.

Step 3:

Invoke the WCF service on the button click event, Make sure you set the expected data type as XML

        function CountryProvinceWCFJSONMulti() {
            var browser = "";
            if (jQuery.browser.mozilla == true) browser="firefox"
            else if(jQuery.browser.msie == true) browser = "ie"
            varType                = "POST";
            varUrl                   = "service/CountryProvinceWCFService.svc/GetProvinceAndBrowser";
            //We are passing multiple paramers to the service in json format {"Country" : "india", "Browser":"ie"}
            varData                = '{"Country": "' + $('#ddlCountry').val() + '","Browser": "' + browser + '"}';
            varContentType   = "application/json; charset=utf-8";
            varDataType        = "json";varProcessData = true; CallService();
    }

Step 4:

On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.

  function ServiceSucceeded(result) {
                    var ProvinceDDL = document.getElementById("ddlProvince");
                    for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }                   
                   //WCF Service with multiple output paramaetrs //First object
                    var resultObject = result.GetProvinceAndBrowserResult.ProvinceInfo;
                    for (i = 0; i < resultObject.length; i++) {
                        var opt = document.createElement("option"); opt.text = resultObject[i];
                        ProvinceDDL.options.add(opt)
                    }
                    //Second object sent in JSON format
                    $("#divMulti").html(result.GetProvinceAndBrowserResult.BrowserInfo);          
                }


5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format

This time we will use GET Verb instead of POST to retrieve the data through WCF & jQuery

Step 1:

    We can use the WebGet attribute instead of WebInvoke to perform the operation,
    [OperationContract]
    [WebGet(ResponseFormat=WebMessageFormat.Json)]
    string[] GetProvinceGET(string Country);

Implement the contract

    public string[] GetProvinceGET(string Country)
    {return new CountryProvinceBL().GetProvince(Country);}

And use the web.config defined in figure 1

Step 2:

      Set the verb to GET instead of POST and pass the data as a query string. Invoke the WCF Service using below method
        function CountryProvinceWCFJSONGet() {
            varType                 = "GET";
            varUrl                    = "service/CountryProvinceWCFService.svc/GetProvinceGET?Country=" +$('#ddlCountry').val();
            varContentType    = "application/json; charset=utf-8";
            varDataType = "json";varProcessData = false; CallService();
        }

On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.

       function ServiceSucceeded(result) {
           var ProvinceDDL = document.getElementById("ddlProvince");
           for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }         
           for (i = 0; i < result.length; i++) {
               var opt = document.createElement("option"); opt.text = result[i];
               ProvinceDDL.options.add(opt)
           }
       }


6. Calling REST based WCF service using jQuery


 Step 1:

Define the URI for REST service in the operation contract and set the BodyStyle to Bare.

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProvinceREST/{Country}", BodyStyle=WebMessageBodyStyle.Bare)]
    string[] GetProvinceREST(string Country);

Implement the contract:

    public string[] GetProvinceREST(string Country)
    { return new CountryProvinceBL().GetProvince(Country);  }

Use the web.config defined in Figure 1

Step 2:

While using REST services use GET verb for retrieving data and POST , PUT , DELETE for modifying, adding and deleting information
        function CountryProvinceWCFREST() {
            varType               = "GET";
            varUrl                  = "service/CountryProvinceWCFService.svc/GetProvinceREST/" + $('#ddlCountry').val();            
            varContentType  = "application/json; charset=utf-8";
            varDataType       = "json"; varProcessData = false; CallService();
        }

On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.

       function ServiceSucceeded(result) {
           var ProvinceDDL = document.getElementById("ddlProvince");
           for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }          
           for (i = 0; i < result.length; i++) {
               var opt = document.createElement("option"); opt.text = result[i];
               ProvinceDDL.options.add(opt)
           }
       }

7. Stream an image through WCF and request  it through HTTP GET Verb


2 WCF Image.jpg
Step 1:

Define the contract and set the return type to Stream since we are going to send it in Image/jpeg Format  
    [OperationContract]
    [WebInvoke(Method = "GET")]
    Stream GetPicture();

Implement the contract

    public Stream GetPicture()
    {
        string fileName = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");
        FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);  
       // Set the content type as image/ jpeg
        System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
        return (Stream)fileStream;
    }

And use the web.config which we defined earlier in this article

Step 2:

On Button  click event set the src attribute of  image element [image1] to  the WCF service
   <img src=""  id="image1" width="500" height="400" />

 function ShowImage() {// Call the WCF service
            $("#image1").attr('src','service/CountryProvinceWCFService.svc/GetPicture');
          
        }

Conclusion:

Thanks for reading the article, I know that I have not gone into the details of each and every aspect to keep the article shorter. Please download the source code to check the examples yourself, I have validated the example in IE 7 and Firefox 3.5. If you have any suggestions / comments / doubts regarding the article don't hesitate to post it.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Sridhar Subramanian
Sridhar is working in Software field since 2000. He has good experience in Microsoft .NET and web related technologies.

www.newsdabba.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Thank for your article by Kyaw Ko Ko On February 21, 2010
I find the topic using web services  from JavaScript before.Thank a lot.
Reply | Email | Modify 
Re: Thank for your article by Sridhar On February 23, 2010
You are welcome.
Reply | Email | Modify 
Great article by Mahesh On February 24, 2010
Great article Sridhar. Thank you for sharing. I have just started working with Jquery and found it useful.

Cheers!
Reply | Email | Modify 
Re: Great article by Sridhar On February 25, 2010
Thanks Mahesh.
Reply | Email | Modify 
Realy need full by anil On February 27, 2010
Very very good helpfull information in a singhle article
Reply | Email | Modify 
Realy need full by anil On February 27, 2010
Very very good helpfull information in a singhle article
Reply | Email | Modify 
Re: Realy need full by Sridhar On February 28, 2010
Thanks Anil.

Reply | Email | Modify 
Thank You! by Joe On April 3, 2010
This is a fantastic article, and I really appreciate it! Thank you!!!
Reply | Email | Modify 
Re: Thank You! by Sridhar On April 6, 2010
Thanks Joe.
Reply | Email | Modify 
Trouble with Firefox by vic On May 4, 2010
Sridhar,
Your article was very helpful.  I used option 2 as a basis for my own service as was able to get it working perfectly in IE8.  However Firefox (3.6.3) is returning 401 Unauthorized when I analyze it with Fiddler.  Any ideas on how to overcome this?  Please note that I am making the jquery calls from within a sharepoint page, and as such had to install the service on a separate IIS website (using the same domain but a different port number).  So my function looks something like this:
        function GetEmail() {
            varType = "POST";
            varUrl = http://server:9999/peoplesearch/Service.svc/GetEmail;
            varData = '{"name'"}';
            varContentType = "application/json; charset=utf-8";
            varDataType = "json";
            varProcessData = true;
            CallService();
        }

Any clues you could offer would be much appreciated.
Reply | Email | Modify 
Re: Trouble with Firefox by Sridhar On May 4, 2010
I think Firefox considers it as a cross-domain post, Can you try with the GET method 5th one, it should work.


Reply | Email | Modify 
Re: Re: Trouble with Firefox by vic On May 5, 2010
Thanks for your reply, Sridhar.  My initial attempt to switch to method 2 (GET) did not work in IE or Firefox.  I must be missing something.  I will try downloading your code to see where I'm going wrong.  Thanks again.
Reply | Email | Modify 
Re: Trouble with Firefox by Sridhar On May 4, 2010
Vic:<br>Also check whether your session is authenticated in firefox.<br>
Reply | Email | Modify 
Re: Re: Trouble with Firefox by bhaskar On August 25, 2010

Hi Sridhar,

Thanks for this wonderful post. Can you help me in securing WCf call from Jquery as i am still stuck about its security aspect.

When a web application webpage uses Jquery to access JSON packets from WCF Rest service, how can we implement security(authentication) in this.

If we put both webservice and webpage in the same web application(in Visual studio), they share the same httpcontext using aspnetcompatibility attribute, but when they don't share same appdomain, what is the way to do authentication in WCF Rest service.

I have tried looking into WCF REST kit but it also don't have solution to this

Hope i am able to put my query right, otherwise please let me know

Cheers

TicArch

Reply | Email | Modify 
Thanks for Shariing your expertise by Ravi On September 2, 2010
Thanks a lot for this very easy to get article.
Reply | Email | Modify 
Thanks for article by aashi On December 27, 2010
Its gudlot
Reply | Email | Modify 
One stop shopping ;-) by jo On February 11, 2011
Thank you very much for these practical examples you have provided !!! I was looking for a quick solution to get jQuery talk to my WCF. You covered different HTTP methods and different jQuery method overloads. Keep on that nice work!
Reply | Email | Modify 
Thank for your article by Mario On February 15, 2011
Thank a lot.
Reply | Email | Modify 
. by JM On March 1, 2011
.
Reply | Email | Modify 
Very Good Article by Atul On April 8, 2011
Hi Sridhar, It is very good article and very helpful.
Reply | Email | Modify 
400: Bad Request error by Charudatt On April 8, 2011
I am trying for WCF service using JQuery[ Get Method] and get data in JSON Format, but geting 400: Bad Request error. Any help will be much appreciated
Reply | Email | Modify 
Thank you ! by Farooq On December 19, 2011
Thank you for posting
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.