Aug 19

JQuery: full control with the $.ajax function

Posted in JQuery      Comments Off on JQuery: full control with the $.ajax function

In the previous posts, we’ve met several helper methods which simplify the code needed to perform remote out-of-band requests. In this post, we’ll be introducing the all mighty $.ajax method. This method is used by all the other methods we’ve seen until now and gives you complete control over the request.

Currently, you’re supposed to use an anonymous object to pass all those definitions (which are really a lot!). To illustrate the use of this method, we’ll be consuming a ASP.NET web service which returns JSON. We’ll start with the service code (defined on the SayHiService.asmx(.cs) file):

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SayHiService : System.Web.Services.WebService {
    public User SayHello(String name) {
        return new User {
            Name = name,
            Date = DateTime.Now
public class User {
    public String Name { get; set; }
    public DateTime Date { get; set; }

We’ve created a simple User class that will return a user and the current time at which the request was received on the server. If you’re into ASP.NET AJAX, then you’ll know that it uses JavascriptSerializer to serialize the return value into JSON. In the client side, you’re expected to transform the returned JSON into an object by using the Sys.SerializationJavaScriptSerializer JS class.

If you’re consuming ASP.NET web services from client code, there are some aspects you should keep in mind:

  • the returned object is wrapped into  an anonymous object with a single property (called d). This means that you’ll always receive a JSON string which looks like “{ ‘d’: … }”;
  • DateTime fields are transformed into /Date(x)/, where x is the number of ms elapsed since Jan. 1, 1970 at midnight UTC. In practice, this means that you’ll have to recover x and transform it into a valid JS Date object;
  • don’t forget that the web service needs to receive a JSON payload too. This means that you need to set the content type and you do need to serialize (into JSON) the arguments you’re passing from the client. If the method doesn’t receive any parameters,you should send the ‘{}’ string or it won’t work;
  • by default,the web service will only respond to POST requests (if you want to open it up to GET requests, you need to use the ScriptMethodAttribute on the web service definition)

If you used the Sys.SerializationJavaScriptSerializer JS class, you don’t have to worry with these details. However, you might not want to load the MS AJAX file just to do the parsing of the returned JSON (btw, I’ve used this approach in an previous post about ASP.NET MVC and JSON). And that’s what we’ll do in this post: we’ll use JQuery and the JSON plugin (which you can download from here) to interact with the previous web service. Here’s the final code of this page:

<input type="text" />
<input type="button" value="Server" />
<script type="text/javascript"> $(function() { $("input[type=button]").click( function(evt) { $.ajax({ url: "SayHiService.asmx/SayHello", type: "post", data: $.toJSON({ name: $("input[type=text]").val() }), contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { var user = data.d; //update date user.Date = new Date( parseInt(user.Date.match( /d+/ )[0] ) ); var html = "Nome: " + user.Name + "--- Date: " + user.Date; $("div").html(html); } }); }); }); </script>

Some observations about the previous code:

  • when calling the web service, you need to indicate the method that you want to invoke. That’s why we passed “SayHiService.asmx/SayHello” to the url property;
  • since I didn’t change the default server configuration, we need to ensure that the request will be made through a POST request (notice the type property);
  • we’re using the $.toJSON utility function to serialize an object which contains the information we want to send back to the server;
  • by passing json to the dataType, we’ll be getting a JS object in our success calback method;
  • the callback method starts by recovering the returned object (remember that we need to access the d property of an anonymous object). Then I used the most simple regular expression possible to recover the x from within the /Date(xxxx)/ string returned from the server side (as a side note, I’m betting that there are better ways of doing this, but regular expressions aren’t really my thing…);
  • you probably should pass a function to the error property so that you cna be notified about errors that have occurred during the request.

I guess there’s more to say about this method, but I think that the previous snippet covers what you’ll be using in 99% of the times. If you have the time, then do take a look at all the available options because there’s some interesting stuff going on there.

And that’s it. Keep tuned for more on JQuery.