Tuesday, September 21, 2010

Binding data on page using Ajax calls (Jquery + Json)- Javascript File & Web Page

2. JavaScript

Creating a method in javascript file using jquery is not a Rocket science. It is as easy as creating a method in any object oriented programming. Learn the syntax all logic is same as in OOPs programming.

1. First method in javascript file should be:

$(document).ready(function()
{
AssessmentArea(); // Add method here that you want to call on document load.
}

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

Ajax call format should be as below :
$.ajax({
type: “POST”,
url: “data.asmx/ListAssesmentArea”
data: “{}”
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
}
});

type:
Default: 'GET'
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

url: Its URL of web-service method.

date: It contains parameters for the method that we are calling in webservice.You can pass parameters in it as shown below.

contentType: When sending data to the server, use this content-type. For Json it is application/json; charset=utf-8.

dataType: Data to be sent to the server.

success: function(data): Function that return data if ajax call performed successfully.

function AssessmentArea()
{
$.ajax
({
type: "POST",
url: "data.asmx/ListAssesmentArea",
data: "{AA:'',JJ:'',NH:'',PC:'"+ $("#hdnPC").val() +"',UT:'"+ $("#hdnUT").val() +"',PS:'"+ $("#hdnPS").val() +"',View:'"+ $("#hdnView").val() +"',Characteristics:'"+ $("#hdnLC").val() +"',LALR:'"+ $("#hdnALR").val() +"',Bedroom:'"+ $("#hdnBedrooms").val() +"',Bathroom:'"+ $("#hdnBathrooms").val() +"',FinishedArea:'"+ $("#hdnFA").val() +"',FT:'"+ $("#hdnFT").val() +"',AYB:'"+ $("#hdnAYB").val() +"',EYB:'"+ $("#hdnEYB").val() +"',AssessmentValue:'"+ $("#hdnAV").val() +"',ImprovementValue:'"+ $("#hdnIV").val() +"',TotalValue:'"+ $("#hdnTV").val() +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
var items = "";
var array;
if($("#hdnAA").val() != '')
{
array = $("#hdnAA").val().split(',');
}
for(var index in data)
{
var abc = JSON.parse(data[index]);
var a=0;
jQuery.each(abc, function(rec)
{
var str = "";
for(var Id in array)
{
if(array[Id] == this.pr_aa_codeid)
{
str = "checked='checked'" ;
break;
}
}
});
}

$("#dvAssesmentArea").html(items);
},
error: function(xhr, status, error)
{
}
});
}

JSON.parse() : This method is used to convert Json formated string to object. So that it can be read easily.


3. Webpage:

1. Add latest jquery libraries to your application & add refrence of below javascript files on your page:

// This namespace contains method that reformat the Json formated string to object.
// This is our jquery file.

So now your page has only this DIV and data is loading from JS file.

I'll soon add a link to download sample application. Till then try it your self :-)


Cheers,
Vikas Sharma

Binding data on page using Ajax calls (Jquery + Json)- The web-service


Few days back i got a requirement to create a page that has around 200 controls and each control's value refreshes when i click on any one of it. I first tried it using server side code but it was taking too much load and i find it difficult to do it in that way.

I am not familier with javascript programming. but i decided to make it using Jquery & Json.What i know about both is as follow:

1. jQuery: The Write Less, Do More, JavaScript Library

2. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

It takes a lot of time for me to do it in this way. but it make me confident that i am writing this blog and sharing my experience.

Lets see what you think about it :-) , Please post your comments.


This application contains below three parts:

1.Web Service
2.Javascript File
3.Web Page

Here we are creating the first part - The Web-Service

Web Service: It can be a Normal Asp.net web-service or WCF web service, you can select between it according to your requirement. I was not so familier with WCF thats why I selected a simple web service for my project.

Add Namespaces first in asmx class:
1. using System.Web.Script.Services;
2. using System.Web.Script.Serialization;


Why do we need these namespaces?
Well lets start with System.Web.Script.Services namespace. We are using it for adding response formats to the methods ie:- json. It contains Enum for it and contains two values in it ie:- Json & xml. So we get Json return type from this namespace.

Now System.Web.Script.Serialization, It contains classes that provide Javascript Object Notation (JSON) serialization and deserialization for managed type.we are using serialize method of JavaScriptSerializer class. So we get the method to serialize our object from System.Web.Script.Serialization namespace.


How is my webservice going to respond to the ajax calls?
To enable webservice to respond to ajax call uncomment below “[System.Web.Script.Services.ScriptService]” written on the top of the webservice class.

Method: Below is example to web method that return Json format, create a method using these syntax with json return type:














Don't worry about the properties in method , they are just for my game.

So lets discuss this method. As you can see return type is on the top of the method
“[ScriptMethod(ResponseFormat = ResponseFormat.Json)]”. At the end of the method you can see that we are using a List collection and converting it into Json formated string using serialize method of JavaScriptSerializer class.

So here my web service is ready for Ajax calls. Check out my next post for Application part.

Cheers,
Vikas Sharma