Published: 30 Sep 2009
By: Brian Mains

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.

Contents [hide]

Using WebServiceProxy

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 multipart/form-data or application/x-www-form-urlencoded, whereas for METHOD="GET", only application/x-www-form-urlencoded is allowed. This form data set is then transmitted to the server."

JQuery Get

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.

JQuery Post

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:

stocksymbol=MSFT&stockprice=%2450.00

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

Notice the $(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.

JQuery getJSON

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 StockPrice and 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.

Using AJAX

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:

http://api.flickr.com/services/feeds/photos_public.gne?tags=penguins&tagmode=any&format=json&jsoncallback=?

This will return image results for images tagged with the "penguins" tag and return the results back to the server in JavaScript Object Notation (JSON) format, which is represented by curly braces ({}). The task will be to make the call to the server, process each record in the JSON result set, and write this data to a web page. The sample JSON data that FLICKr returns for each record looks like. Note that this article assumes that you are familiar with JSON.

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 [0] 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.

Conclusion

JQuery makes it very easy to communicate with the server; it works similarly to WebServiceProxy in the way it communicates with the server.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Brian Mains

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.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
Book Review: Pro JavaScript Design Patterns
Brain Mains reviews Pro JavaScript Design Patterns.
Test120Jan
This is my custom article

You might also be interested in the following related blog posts


How To Build Web-Site With AJAX (HTML+CSS+JS+PHP) . . . XHR & jQuery . . .For Beginners read more
jQuery DataTable with AJAX on ASP.NET read more
Learn ASP.NET MVC with jQuery and AngularJS Ajax in Thane read more
Learn ASP.NET MVC with jQuery and AngularJS Ajax in Thane read more
Upload Files in ASP.NET MVC 6 (Form POST and jQuery Ajax) read more
Upload Files in ASP.NET MVC 6 (Form POST and jQuery Ajax) read more
Dynamic Content Load, using jQuery AJAX read more
Use Global Ajax Event Handler Methods in jQuery read more
Use Global Ajax Event Handler Methods in jQuery read more
How to Insert HTML Table Data into SQL Server in a Single Batch by Using JQuery Ajax and Structured Parameter read more
Top
 
 
 

Please login to rate or to leave a comment.