Using jQuery with ASP.NET Part 2: Making an AJAX Callback to ASP.NET
This time around I’ll expand on these concepts and show you how you can use jQuery in combination with ASP.NET as an AJAX backend to retrieve data. I’ll also discuss how you can create ASP.NET controls and otherwise interact with jQuery content from ASP.NET pages in Web Forms.
In the first part of this article series I introduced jQuery’s functionality and how it provides a rich client-side programming model.
In this article I’m not going to be talking much about ASP.NET AJAX since that’s been covered ad infinitum in other places-the procedure doesn’t vary much if you’re using ASP.NET AJAX with jQuery. Instead I’ll focus on using purely jQuery on the client without the ASP.NET AJAX client library, and I’ll provide a few small helpers that I’ll describe below to make callbacks to the server easily. In the process you’ll get to see how some of jQuery’s AJAX features work.
First AJAX Steps with jQuery
This the low-level AJAX function with many, many options that lets you create just about any kind of AJAX request. If you need full control over requests or you want to create a generic component that calls back to the server (like the WCF/ASMX client proxy I’ll discuss later) you’ll want to use this function. For now check out the documentation (http://tinyurl.com/4mcnaa) on the multitude of options available.
The .load() function is the only AJAX function that works off a jQuery selector. It calls a URL on the server and loads the result as content into selected element(s). It’s a very quick and easy way to load HTML fragments and inject them into the client HTML document. You can provide an optional callback to be notified with the server result text when the callback completes, which is useful if you want to visually adjust the retrieved content-like applying an effect to visually cue the user to an update.
These functions are simple helpers that provide basic get and post operations to the server. You specify a URL and a callback, which is called with the HTTP response from the server. $.post() also allows you to pass either a formatted POST buffer string or an object the properties of which are turned into POST encoded key value pairs.
.getJSON() also supports cross-domain JSONP callbacks. If you specify a query string parameter of callback=? you can force the result to be routed to the callback you specify in the parameter list.
Global AJAX Events
There are also a number of global AJAX events that you can take advantage of, all of which take callbacks as parameters: ajaxCallback(), ajaxError(), ajaxSend(), ajaxStart(), ajaxStop(), and ajaxSuccess(). These are useful for setting up global handlers that can centrally manage AJAX requests. You’re not likely to need these much unless you build components that need to know status of requests.