Total votes: 0
Print: Print Article
Please login to rate or to leave a comment.
Published: 30 Sep 2009
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post() methods as a way to retrieve data from the server. We’ll examine how it’s used here, and how it differs from how ASP.NET AJAX has done web requests.
For those used to ASP.NET AJAX, Microsoft provided a way to communicate with the server. This capability can be easily done using the Sys.Net.WebServiceProxy, which uses the native object to make an XmlHttpRequest to the server, extract the information, and make the response available in a callback (or any corresponding error information if the request fails). This can be done using the following code, assuming a web service is in place in the following location.
Listing 1: Using WebServiceProxy
The Sys.Net.WebServiceProxy information takes the following information:
path – The location to the web service (URL).
methodName – The name of the method to execute on the web service
useHttpGet – Whether to use get or post, a boolean value.
Parameters – The parameter values that will be assigned to the method's parameter list on the server. The parameters are named (in name/value pair form).
succeededCallback – The callback method to call when the web request succeeds. All web service features use a callback approach because these calls must be asynchronous. The signature of the callback is: response, context, method.
failedCallback – The callback method to call when the web request succeeds. The response variable will be the exception details.
userContext – The context variable – this is a general variable for usage.
Timeout – The timeout for the method call; if an operation call takes longer than the timeout, the web request will fail.
Using this information, the WebServiceProxy class makes a call to the server, at that location or method. This request includes the HTTP verb for the operation type, which can be get, post, put, delete, etc. A connection to the server is made, the response is returned to a callback method (upon success). The data retrieved from the server, whether XML or JSON, is returned to the specified callback method, and the data can therefore be processed.
WebServiceProxy is a popular option, especially when creating an ASMX web service with the ScriptService attribute defined. This creates a proxy class that wraps WebServiceProxy as a way to generate a strongly-typed proxy class.
Get vs. Post
You may wonder what the difference is between get request and post requests. The request header for a request contains this HTTP verb that identifies the type of request to perform. The general recommendation is a request made via a get request for getting data (reading from a database, for instance), and post requests for updating data (insert/update operations to a database, for instance). You can get a nice overview from the following web site: http://www.diffen.com/difference/Get_vs_Post
That site had a good description on the differences, that GET and POST request "correspond to different HTTP requests, as defined in the HTTP specifications. The submission process for both methods begins in the same way - a form data set is constructed by the browser and then encoded in a manner specified by the
enctype attribute. For
METHOD="POST" the enctype attribute can be
application/x-www-form-urlencoded, whereas for
application/x-www-form-urlencoded is allowed. This form data set is then transmitted to the server."
JQuery can retrieve data using a GET operation using the get method. Using the get option is a synch:
Listing 2: Using Get to write data to the page
The get option posts back to the server using a GET operation and uses the response of the request to replace the actual content of the page. That's the purpose of
replaceWith; it takes a reference to an element with an ID of
LinkagePanel, and replaces its content with the response. So simple. But realize this does assume that the response being returned is an HTML content in string form.
The data formats returned from a get response could be a variety of content formats (such as XML or JSON, for instance). The key point to note here is that the get method returns its data in a string form. There is another alternative that I'll mention later.
Posting data to the server is a common response. After all, ASP.NET web forms posts data to the server on every post back. The results of the posted form elements are available in the
LoadPostData method response, which the page handles automatically (you would only need to be involved for activities like developing a custom control and some other advanced scenarios). This
postback collection contains a key/value pairing of values for every control on the page, and ends up being quite the huge list of entries.
JQuery supports posting to the server too, but AJAX solutions to posting to the server (either using JQuery or even WebServiceProxy) are much better over traditional web forms becaue the payload is a lot smaller. The page will run a lot faster (especially for large pages with a large HTML payload) when only the actual data that's needed for the specific action is posted back. Web forms provide additional challenges because ASP.NET web forms uses a global form tag with a runat attribute. This will work fine in HTML- or ASP.NET MVC-based applications.
Posting back a portion of the page can be easily done with JQuery. Imagine this form:
Listing 3: Sample Form
The form has an action to an URL (URL rewriting is enabled in this sample). The two fields within the form get submitted to the server upon clicking the submit button, and the results are posted to the form's action. There are a few things that happen when the page posts back. First, the posted data within the form is available via a format as shown below:
Each field is available in a name/value format, and any special characters are encoded. JQuery performs this post using the following code:
Listing 4: Handling form submit
$(this).serialize() call; this actually produces the name/value pairings (shown above) to be posted back, as the .NET framework would do. This method makes it convenient, supplying the value to the post method that does the work. Also, rather than hard-coding the action, the
attr() JQuery method is used to read it. The last parameter is a callback, taking the response that comes back from the server. The incoming data is a string, and can be used to replace the form's content.
For JSON data, it's more useful to use the
getJSON method. This method has the same signature as the post method, but its JSON data is already available as an object. While a JSON result may be available via POST,
getJSON parses the object for you, and the result is a ready-made object. Check out the code below.
Listing 5: Getting JSON data from the server
In this example, the response parameter is an object with a
StockSymbol properties, and can be used to render to a form element. Note that response is an object directly; with get or post, the content comes back as a string and would have to be eval'd to create the class.
This example that I'm about to show you will use a service that will pull FLICKr images from its server (using a REST service) and download the images to the current browser session. FLICKr provides an easy way to query image data from its server, simply by requesting data using the following URL:
Listing 6: Sample JSON object
Each of these items in the collection represents an image on the FLICKr server. It maintains certain information about that image. The primary references are
media.m to reference the image URL, the
author property to reference the submitter, the
published property to check the publish date, and the
title to reference the image's title.
This object is wrapped in a collection, which is returned as an object in the
items property of the returned object. So, whatever value that comes back from the server, all of the objects are stored in the
items property of that parent object. This is shown in Listing 7. I'll explain the rest afterward.
Listing 7: Retrieving and rendering the UI
JQuery returns the data in the form of a callback, as mentioned above. The
$.each method comes in handy for processing array-based data, taking the array variable as its first parameter, and a callback for each item as its second. Each object can now be referred to by the item variable in the callback. This example uses an existing table structure in the sample UI, and adds additional rows from the image results to the its body tag.
Note that the way that the form is being constructed is using JQuery. The FLICKr data is simply passed to the
html() method of JQuery, so that the contents are rendered directly to a table. JQuery also uses a neat way to create elements, by using the selector syntax but with a full XHTML tag (as in
$(“<span/>")). This syntax creates the objects, assigns it values, and uses the
appendTo method to append it to a parent object. Additionally,
appendTo returns the JQuery object, so using the
 array indexer returns the object that was created (a reference to the
TR object when creating the row and the
TD element when creating the cell). That may take a little bit of getting used to, but it makes it very, very convenient for whipping up dynamic HTML. Pretty cool.
JQuery makes it very easy to communicate with the server; it works similarly to WebServiceProxy in the way it communicates with the server.
Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare.
In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...
This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.
Please login to rate or to leave a comment.