- Boiling jQuery down to the essentials (technique)
- Using jQuery AJAX with a HTTP handler (technique) - this article
- Returning JSON from a HTTP handler (technique)
- Enable Intellisense for Client OM and jQuery (tip)
- Useful tools when building AJAX applications (tip)
- Migrating existing applications to jQuery/AJAX
Let’s consider the server side first - there are a couple of options:
- Write a WCF service (or indeed, ‘classic’ .asmx web service)
- Write a HTTP handler
- Write some other form of server code which (like the others) generates a response over HTTP
- e.g. technically a good old .aspx page could work as the server-side component. However, this is a bad choice compared to the other options for a few reasons (mentioned shortly)
Arguably the purist route would be to develop a WCF service – indeed SharePoint 2010’s implementation of the Client OM is a WCF service. If you’re experienced with WCF, this is probably a good choice for you. However, my view is that a HTTP handler is a hundred times simpler, and that the features of WCF (e.g. transport flexibility, ability to pass large files, security etc.) are typically not necessary in an “internal to the farm” SP2010/AJAX app. Of course, if you’re building a public API to expose stock quotes to the world then things might be different. Alternatively, an esoteric approach could be to use something like a regular .aspx page – however an ASP.Net web forms page (i.e. not MVC) will be less efficient here as the page will go through the full ASP.Net lifecycle (Init, OnPreRender, Render etc.) despite the fact you probably don’t have any ASP.Net controls on the page. In other words we are using ASP.Net pages for something other than what they were designed.
So, a HTTP handler is a simple and effective means of building an AJAX-style app. To some folks it’s a new technique, and for others it’s old news – but it’s my view that this approach is THE key to unlocking the ability to write AJAX apps, whether that’s on top of SharePoint or plain .Net.
The great thing about this technique is that the possibilities are unlimited – you can AJAX-ify anything, since you would write the C# code in the handler, then just call it from jQuery. Clearly this cannot be said about a ‘provided’ API such as the Client OM. By the way, I’d be interested to hear opposing opinions on the WCF vs. HTTP handler point.
|$.get()||Requests a URL using a HTTP GET – calls .ajax() underneath|
|$.post()||Requests a URL using a HTTP POST – calls .ajax() underneath|
|$.ajax()||Allows full control – exposes full set of parameters|
|$.getJson()||Requests a URL GET and parses response for JSON format using $.parseJSON|
Creating a HTTP handler (server)
So, we’ve hopefully established that a HTTP handler combined with jQuery’s AJAX methods is a powerful technique – now let’s look at the detail.
A HTTP handler is a .Net class which implements System.Web.IHttpHandler – the ProcessRequest() method is the main method. Here, you write code which determines what is returned when the URL for the handler is requested. So where a URL to an .aspx page would return HTML, you can return whatever you want – a simple string, some more complex XML, or perhaps JSON (the next article in this series). A simple handler returning a string looks like this:
The .Net framework needs to know about such a handler before it can be used. Two options here – either associate an .ashx file with your .cs file above (the handler is called by the path to the .ashx in this scenario), or add a web.config entry telling .Net how to route the request to your class (the handler is called by whatever path you define in web.config in this scenario).
Using an .ashx
Create a file in your project with an .ashx extension (there is no VS item template, unless I keep missing it), and use the WebHandler directive to point to your implementation. This works because .ashx is a special extension where .Net knows to resolve the class by looking for the WebHandler directive:
Using a web.config entry
Add an entry (e.g. via SPWebConfigModification) like this – notice you can specify a custom path/extension if that’s preferable for any reason:
Most folks opt for the .ashx route since it avoids defining something in web.config for every handler your application uses.
Calling a HTTP handler (client)
Earlier, we detailed jQuery’s four core methods for making a request to the server. Here’s an example (using the .get() method):
As you can see, the key is taking the data property which is passed from the server to the jQuery callback, and using jQuery’s ability to manipulate the page with methods like .html(). Hey presto, you can now do anything you like without a full postback!
Something to note is that if you’re modifying data in the handler, a good practice is to make it a .post() request rather than .get() – of course, SharePoint disallows updates on a GET request by default so you must do something to work around this anyway (the ghetto alternative being to set SPWeb.AllowUnsafeUpdates = true).
Putting it into practice
Now that we’ve learnt the mechanisms, consider how usage might pan out in the real-world:
- Return data:
- If you’re returning unstructured data (e.g. a string), things are pretty simple (N.B. another jQuery AJAX method I omitted to mention is $.load() method which simplifies things further)
- For structured data (e.g. objects), this is often returned as a JSON-serialized string – commonly preferred to XML, but there are plenty of samples out there for XML too
- Because setting the HTML of a page element is so easy, it’s tempting to have a handler return a huge string of hardcoded HTML (e.g. when we’re updating a big complex area of the page) – indeed I mentioned this as a “SP2010/jQuery/AJAX survivor’s technique” in my SharePoint Saturday talk. This works fine but a far better approach is to use the new jQuery templates capability – Jan Tielen’s Getting Started with jQuery Templates and SharePoint 2010 is a great post.
- A good way to structure your code is to have a handler implement multiple methods (e.g. for related functionality), and pass a querystring parameter in the AJAX request to indicate which method to execute. You certainly don’t need a handler for every method you might implement.
Next time - Returning JSON from a HTTP handler