Thursday, January 16, 2014

Simple way of accessing REST / JSON service and formating a response using JQUERY

In this article I am not going to explain you how to create REST/ JSON webservice . But the client code which uses to draw a response to a html page .

Consider following json object array comes with a webservice response.

[{"Name":"hasitha","Age":27},{"Name":"harshana","Age":28},{"Name":"sampath","Age":27}]

Assume that result generated with following web service .
http://yourdomain/Employees

Jquery comes with very simple highlevel code snippet which can use to execute ajax 
requests.Most basic version of that function is $.ajax({}).
Lets modify it by pieces to achieve our task. First we needs to define the 
http request method type(often call it http verb) . There are few commonly use types,
GET/POST/PUT/DELETE

Since we are requesting data from server , the service in this sample 
should be a GET request.
Then we need to tell the code , from where we get our resource . That is service URI link . "Employees"
Third property is contenttype . There are few commonly use content types .
 XML , JSON ,TEXT/HTML etc . 
In our case since the service return json data , contenttype should be
 "application/json" .
Last property is data . Along with data ,can pass whatever the data(parameters)
needs by service . In this simple case have not define anything .

 $.ajax({
            type:"GET",
            url: "employees",
            contenttype:"application/json",
            data: {}
        });


Now after the request process ,service returns data as expected once the request
processed without issues . From the client side we have to define callback handler 
to capture the response and make the visual formatting .
In this example I use simple html table .

<table id="employeesTbl">
 </table>

I should populate the table using 3 records returned by service , with in callback
 handler .
FULL CODE
<script>
    $(document).ready(function () {
        console.log('in');
        $.ajax({
            type:"GET",
            url: "employees",
            contenttype:"application/json",
            data: {}
        })
.done(function (data) {
    if (console && console.log) {
        console.log("Sample of data:", data);
    }
    output = "";
   // data = $.parseJSON(data);
    $.each(data, function (i, item) {
        output += "<tr><td>" + item.Name + "</td></tr>"
    });
    $("#employeesTbl").html(output);

});
});
</script>



Note that I used $.each function to iterate through records array . 
Dynamic output variable holds a html content created . After completion , 
the created text content should pass in to the body of the html table element.

"console.log()" statement can use for debugging purpose , where we can inspect 
and test the code with any browser plugins like firebug / chrome inspector.

There are few templating plugins available for jquery for html formatting . But in this sample I kept the code much simpler , to understand the scenario clearly.


Hope this helps.

No comments:

Post a Comment