How to call WCF Services in AJAX

JavaScript can communicate with services in JSON(JavaScript Object Notation) format. JSON is the best serialization format in performance and preferred wherever possible because of this fact. WCF supports JSON format because of which its services can be accessed by any AJAX clients.

To make a WCF service AJAX-enabled, we can use the WebServiceHostFactory class in ServiceHost directive of the .svc file or else create an ajax endpoint with WebHttpBinding and configure it accordingly.

In VS.NET, creating AJAX-enabled WCF Service is really made easy by providing a separate template for the purpose. When we use this template VS.NET takes care of configuring the right endpoints and behaviours. It creates a new system.serviceModel tag in web.config for this purpose. Moreover, all the parameters and results are serialized in JSON format when this template is used.


In this demo we create an Ajax-enabled WCF service and consume it from ASP.NET AJAX.

Our aim in this program is to show that when we input a country name in the text box and press the html button, it should fetch the details of that country from the WCF service and display them to the user. For this we need to create a AJAX-enabled WCF service as we are interacting with the service through JavaScript. The steps for our demo are as follows:

First Create DataBase and add table as follows

Then Enter Data into table as follows:

1. Start a website normally and create the forms and databases as required.

Here we design a form with a html texbox and button to input the Player name. The results will be displayed in the provided label and image html controls.

The form looks as given below:

2. For our service we’ll use EDM for accessing data from SQL Database. We have a database called Countries from which we need to get details from Images table. To create an Entity Data Model right click the project in Solution Explorer and select Add New Item ADO.NET Entity Data Model and give name as CountriesModel. Then select Generate from Database option and choose the required database. In the final step choose the tables you want the data from. In

our demo we have selected Images from Countries database. This step will create an object of our table in the program. The advantage of usingentities here is that they are automatically serialized and there is no need of using [DataContract] attribute for them.

3. Now we’ll create a WCF service which retrieves the data and provides to the clients. For this again from Add New Item, choose AJAX-enabled WCF Service and name it as CountriesService.

This step will create a .svc file which is needed for our service get hosted in IIS. It will also create endpoints for the service with WebHttpBinding and its behaviours. This can be seen in web.config file as follows:

4. Along with .svc file, by default a .cs file with the same is created in App_Code folder to write the code. In this file we write methods necessary to get data from the Entities.

Whatever methods need to be exposed to the client should be decorated with [OperationContract] attributes.

We write the following method in our service:

    public List<string> GetData(string name)
        MySampleDBModel.MySampleDBEntities obj = new MySampleDBModel.MySampleDBEntities();
        var x = (from n in obj.Images where n.PlayerName == name select n).FirstOrDefault();
        List<string> str = new List<string>();
        if (x != null)
            return str;
            return null;

This method gets the details of a given country from the created entities and returns in the form of a list.

Now the WCF service is ready and all that is remaining is to consume it from our web form using JavaScript which can interact with the service asynchronously.

5. For consuming, write the following code in the page source:

function Button1_onclick() {
            Service.GetData($get("Text1").value, f1, f2);
        function f1(res) {
            if (res != null) {
                $get("Label1").innerHTML = res[0];
                $get("Label2").innerHTML = res[1];
                $get("Label3").innerHTML = res[2];
                var img = document.getElementById("image1");
                img.src = res[3];
            else {
                alert("Details for this Player don't exist in our database");
        function f2() {
            alert("Error in processing.. Please try again!!");

Now let’s try to understand this script. For this we should know what controls are placed in the form. Removing table formatting, the source view of the controls is shown below:

  1. <div>
  2. <asp:ScriptManager ID="ScriptManager1" runat="server">
  3. <Services>
  4. <asp:ServiceReference Path="~/Service.svc" />
  5. </Services>
  6. </asp:ScriptManager>
  7. </div>
  8. </form>
  9. <table>
  10. <tr>
  11. <td>
  12. &nbsp;</td>
  13. <td style="background-color: #99CCFF; font-weight: bold;">
  14. <input id="Text1" type="text" /><input id="Button1" type="button"
  15. value="Submit" onclick="return Button1_onclick()" /></td>
  16. <td>
  17. &nbsp;</td>
  18. </tr>
  19. <tr>
  20. <td>
  21. &nbsp;</td>
  22. <td style="background-color: #99CCFF; font-weight: bold;">
  23. PlayerName:<label id="Label1" ></label></td>
  24. <td>
  25. &nbsp;</td>
  26. </tr>
  27. <tr>
  28. <td>
  29. &nbsp;</td>
  30. <td style="background-color: #99CCFF; font-weight: bold;">
  31. PlayerCountry:<label id="Label2"></label></td>
  32. <td>
  33. &nbsp;</td>
  34. </tr>
  35. <tr>
  36. <td>
  37. &nbsp;</td>
  38. <td style="background-color: #99CCFF; font-weight: bold;">
  39. Play:<label id="Label3"></label></td>
  40. <td>
  41. &nbsp;</td>
  42. </tr>
  43. <tr>
  44. <td>
  45. &nbsp;</td>
  46. <td style="background-color: #99CCFF; font-weight: bold;">
  47. Image:<img alt="" src="" id="image1" /></td>
  48. <td>
  49. &nbsp;</td>
  50. </tr>
  51. </table>

When the button is clicked the code in function Btn_Click() is executed. The WCF service is called in that function. To call a service, a ScriptManager is needed which creates the needed proxy to interact with the service. The Service Reference should be provided in ScriptManager as follows:

  1. <asp:ScriptManager ID="ScriptManager1" runat="server">
  2. <Services>
  3. <asp:ServiceReference Path="~/Service.svc" />
  4. </Services>
  5. </asp:ScriptManager>


When the service reference is assigned and the program is compiled, it will create a proxy in JavaScript, through which the function interacts with the service. The following line in Btn_Click function is mainly responsible for providing the result.

  1. Service.GetData($get("Text1").value, f1, f2);

Country.value is the parameter i.e. country name that we are passing to the method. Success and failure are the parameters which represent the functions that are called respectively when the method is executed successfully or failed.

The parameter x passed in the function success(x) is the result obtained from the method GetDetails(). This result is assigned to relevant controls in this function. When the method fails to execute properly, the function failure() is called.

The final result is as shown in the screenshot below:


4 thoughts on “How to call WCF Services in AJAX

  1. Hi there to all, the contents existing at this website are actually
    amazing for people experience, well, keep up the nice work fellows.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s