NovoGeek's Blog (Archive)

Technical insights of a web geek

Passing complex types to service calls using jQuery & JayRock

Scenario: Consider a web form having several fields, whose values are to be submitted to the server through an AJAX call.

ComplexTypes

This can be easily achieved using jQuery’s $.ajax(), passing all the form elements (like first name, last name, city etc) as parameters to the AJAX call.

However, in reality, most of our web forms contain large number of input fields and hence the $.ajax() method will be overloaded with several parameters both at the client side as well as at the server side. This is cumbersome and is not a good programming practice.

Solution: The best practice in this scenario is to build a Data Transfer Object (DTO) on the client side and pass it to the server. This is what Dave Ward explained in his excellent article - “Using complex types to make calling services less… complex”.

If you are working on NET 3.5 framework, Dave’s article is the solution. In .NET 3.5, the System.Web.Script.Services Namespace can be imported, which makes webservices accessible in JavaScript. Also, it has the ability to accept JSON object from client side code and parse it at the server.

However, in .NET 2.0 framework, JSON object cannot be parsed inherently and hence have to use libraries like JayRock. Here is how you can achieve the same using JayRock. The difference is in the way how you pass your “data” parameter in ajax call.

$('#btnSubmit').click(function() {
 
        //Build JSON object by looping through all text boxes
        var objDetails = {};
        $('input[type=text]').each(function() {
            objDetails[this.name] = this.value;
        });
        
        //Stringify the JSON object using the below method from json2.js
        var jsObj = JSON.stringify(objDetails);
 
        //jQuery ajax call. Note the data parameter, which is different from normal ajax parameter.
        $.ajax({
            type: "POST",
            url: "CTypesHandler.ashx",
            data: "{'id':'1','method':'fnAjaxMethod','params':{'obj':" + jsObj + "}}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: fnSuccess,
            error: function(xhr, status, errorThrown) {
                alert('Error' + errorThrown);
            }
        });
 
        function fnSuccess(response) {
            var obj = response.result.details;
            $('#divMessage').html(obj.FirstName + ' ' + obj.LastName + ' resides at ' + obj.City + ', ' + obj.State + ', ' + obj.Country);
        }
    });

Here is a simple demo. You can appreciate the demo if you can see how data is being requested and returned, in json format,  using firebug. (Few optimizations are yet to be done.)

Thanks to Praveen (my Technical Architect) for helping me with the concept. Thanks to Dave for replying to several of my queries.

Pingbacks and trackbacks (2)+

Comments are closed