Wednesday, October 19, 2011

Passing JSON parameters through jQuery

If you’re sending data in your request, use jQuery’s contentType parameter to set the content-type, so that the default is never added:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':’developer’, 'lname':’rocks’}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

ASP.NET AJAX script services and page methods understand and expect input parameters to be serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.

However, if you directly provide a JSON object as the data parameter for an $.ajax call, jQuery will attempt to URL encode the object instead of passing it on to your web service.

Take this sample request, for example:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: {'fname':’developer’, 'lname':’rocks’},
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

Because that data parameter is a valid object literal, calling the web service this way won’t throw any JavaScript errors on the client-side.

You can send it as:

fname=dave&lname=ward

To which, the server will respond with:

Invalid JSON primitive: fname.

This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter, like this:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':’developer’, 'lname':’rocks’}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

It’s a small change in syntax, but makes all the difference. Now, jQuery will leave our JSON object alone and pass the entire string to ASP.NET for parsing on the server side.

Taking these three caveats into account, I think this is the best practice for calling read-only ASP.NET AJAX web services via jQuery:

$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do interesting things here.
  }
});

When consuming web services that require parameters, the usage is similar. Just make sure that you’re passing a JSON object in a string:
$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{'fname':’developer’,'lname':’rocks’}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do magic here.
  }
});
In either of these cases, substitute PageName.aspx for ServiceName.asmx and PageMethodName for WebMethodName if you want to call a page method instead of a web service.

No comments :

Post a Comment