Click here to Skip to main content
15,879,535 members
Articles / Programming Languages / Javascript

WCF Web Service and JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Apr 2011CPOL4 min read 11.5K   4   1
A simple WCF service to send and receive data from JavaScript using jQuery

Over the last week or so, I have been playing around with a simple WCF service to send and receive data from JavaScript using jQuery. I thought that this would be a lot easier than I found it. The other interesting thing I found is that a few people seem to have had trouble getting the two to connect and work. When I set up a standard Service in Visual Studio 2010, I thought it would be easy. You would just use $.ajax to send through the request and wait for an answer from the service. Now, this is probably due to the fact that I am not familiar with WCF, but I thought it would be simple. Well, I found that a few things did not work. So what I have done is created a simple project based in MVC 3 (not that it even matters, since there is only one page on the website), and a service.

So these are my steps to getting jQuery to talk to a WCF service.

Start this off by creating a new project. It can be WebForms or an MVC application. The application type is not the most important part. As long as it is a web style project.

Creating the Service

Once you have created a solution, add a new WCF service to the project.

177975/new.png

When I created the service, I added it to a service folder to keep it separate from the rest of the web project. I find it makes it easy to find if there are any changes that need to be made. There should be three files in the folder: an interface, the svc service, and the service code behind.

Disclaimer: I had a lot of issues getting the service to work with the interface. I found that when I deleted it and just worked with the service, it worked. I am not saying that it will not work with the interface. I just could not get it to work. So if anyone has information on how to get it working, please let me know.

So before I started trying to connect the JavaScript to the service, I went to the service page to make sure it was working the way I expected. You should get the following page:

177975/service.png

I found this useful since any errors will be shown and may save you a lot of hassle before trying to connect the JavaScript. One thing to note is that you need to have at least one method or operation contract, or the service will return an error. There should be one by default when you create the service. If you have deleted the interface, remember to add the [OperationContract] onto the method before checking to see the service works.

There are some changes needed to make the service work:

  • On the class definition, add the following: [ServiceBehavior(IncludeExceptionDetailInFaults = true)]. This will make sure that if there are any errors, the exception will be sent to the JavaScript. I found this really useful when debugging errors.
  • [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  • Right click on the Service.svc file and select View Markup. Add Factory=”System.ServiceModel.Activation.WebScriptServiceHostFactory” in the ServiceHost definition.

Connecting With JavaScript

This was the easiest part for me. There are two methods that I used here: the first obviously was jQuery. I used $.ajax to call the WCF service. You can find the jQuery documentation on the AJAX call here: jQuery Page.

The second thing I use is the JSON library. This can be found at http://www.JSON.org/. The method I use here is stringify. This converts a JavaScript object to a JSON string.

JavaScript
$.ajax({
url: url, //Url of the Service
type: "POST",  //Type of ajax call
data: JSON2.stringify({ value: "value" }),  //Data to send
processData: true,
contentType: "application/json", //Type of data being sent
timeout: 10000,
dataType: "json",
success: function (response, status) { //Success Callback
//Do Something cool here
}
},
error: function (request, textStatus, error) { //Error callback
alert("An unexpected error occurred");
}
}
);

JSONP

I would like to take the time to look into JSONP. Normally, you are not allowed cross domain calls using normal JSON. JSONP stands for JSON with padding. The way this works is by wrapping the JSON response in script tags. The way this works is that when you call the sever, you add a JSONP at the end of the url, i.e., www.url.com?jsonp=callback. When the server responds to the call, it will wrap the JSON response in the method call you specified. So in this example, the response would be callback({ “property” : “valueDefined” });.

When you implement the callback function, all you would do is call the callback method in the following way:

JavaScript
function callback(jsonObject){
    //Do clever stuff here
}

But be warned. This can mean that the service can inject malicious code into the browser. So be careful when using this approach.

This article was originally posted at http://www.makecodingeasy.com?p=175

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- No messages could be retrieved (timeout) --