Sunday, July 25, 2010

XMLHTTPJSClass - JSON Class for Ajax Operations

In the development of Ajax application many times we may come across following issues.
  • Need to update multiple text boxes simultaneously.
  • Fill more that one dropdown lists.
  • Combination of text boxes, dropdown lists and div tags.
  • Calling different web pages and different webservices

Means one event may lead to updating of many html elements. In such cases we will have to send Ajax request in a loop. Again for each request we will have to take care of timeouts and request failures. Here if data is static we can keep it on HTML page and using JavaScript can directly hide and show the contents. But if we have to use real time data and also choices of display vary according to choices of the user, in such case looping of Ajax request may not be a good idea.

In this article we will discuss about XMLHTTPRequest object and JavaScript. We will develop a JavaScript class in which we can vary our choices and also be able to update multiple HTML contents. Also this class can be extended as per the requirements.

We will first talk about class in JavaScript, there is no keyword called class in JavaScript but we can use function as a class.

Checkout following code



In above script if we remove obj.Msg = "HI"; we will get an alert with text Hello.


Now step by step we will start developing our JavaScript class.
1.Include JS file and write following


In this step we have created XMLHTTPRequest object and simply send call to the server. By default method is GET (this.Method = "GET") and calling type is Ascynchronous (this.Async = true)


2.In this step we will develop simple logic which will allow us to dynamically call Ajax function.

For this in our above Ajax function we will add one JSON (www.json.org) object as follows.



In above script we can set the default values for all. Please reffer demo JS file to understand this better. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using "CallPage" : "CallPage.aspx" we can define default server page and while calling Ajax function we can reset this value to web method or to any other web page.
As we will proceed in this article we will come to know how can we change all above values and how can we use it for multiple updation.Also we will see that how to extend the class for further customization.

3.As we have seen in 1st step;

this.request.onreadystatechange=this.handleResponse;
In this step we will develop this.handleResponse function also in this function we will use JSON object defined in 2nd step.
Whenever this.handleResponse function gets call script looses the focus of this. To keep trac of this object we will assing it to some variable. i.e



In this function we will be able to receive data from server. Once we get the data we can play with it the way we want.
This function will take care of the responses from web services as well as from web pages.
Difference is, web service returns response in the form of XML where are response from the webpage can be defined by web developer.

The function will be as follows



If there is any problem in understanding please go through above code again.

In the the 1st step we have



While developing Ajax application take care of following point.
  • URL for XMLHTTPRequest object should belong to same domain.
  • Firefox and other browser doesn’t allow cross domain communication.
  • IE will show warning

Thus our


e.g. "http://localhost/Demo/CallPage.aspx?"+this.JSONArray.Querystring;

Also when ever we want to call web methods like above example, we need to set following protocols under in web.config file.



4.Up to this point we have finished with development of Ajax logic which will return us response. And in this point we will develop logic for population HTML controls

In this.handleResponse (step 3) we have seen that we get response in
“data” variable in JavaScript.

So once we got response from the server we will write following logic



self.JSONArray.isEdit[0].textBoxId will contain id of the text box in which we have to fill the response. And data is the response from the server.
In 2nd step we have defined JSON object as follows



And in our above switch we have simply used the elements of JSON object

At this point we will see how to call our Ajax Class, how to initiate the request and how to set Elements of our JSON object.
Simply create object of our AjaxClass().



if obj.JSONArray.dependentType=1 then our switch case will not work for text box, but it will work for dropdown list (check above switch case). Means we will have to set dropdown list of JSON object.



and so on, we can define our own set of HTML controls to be filled.

In the same way we can change all default settings in JSON object of that class.
e.g. obj.JSONArray.Method = "GET";
obj.JSONArray.CallPage = "Mywebservice/webMethod";
obj.JSONArray.Querystring= "My querystring";

For this URL will be



In case of web service we will have to set CallPage element in the same way we did in above example.

Now for multiple textboxes simple trick,
obj.JSONArray.isEdit[0].textBoxId="txt1$txt2$txtn";//$ is a delimiter
While sending data from server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will get one to one data and textBoxId.

Now we can have different types like “txtbox(es) + drop down list(s) + div” in such case we can use "misc" option of isEdit element of JSON object.
And we can define our PopulateControls function the way we want.

Just think of the choices for getting Response from AjaxCall; we can develop very critical systems using this logic and keeping code as simple as possible. Also we can integrate our ICallback logic for large data transfer.



Demo JavaScript file is as below ( DOWNLOAD)



Download Demo Code here --> XMLHTTPJSClass.zip

Submit this story to DotNetKicks

Read more...

Tuesday, July 13, 2010

CSS- Bubble Tool Tip

Very simple to use bubble tool tip, easy to implement.
I got this code some time back, during my initial phase of web development.



In the body tag put following code




This code is very easy to understand, check style tag and download following images and change the paths accordingly in style tag.



Download Demo Code here --> Bubble Note.zip Submit this story to DotNetKicks

Read more...

Saturday, July 10, 2010

Ajax-Handle complex data type (e.g. Class)

Use of complex data types in Ajax programming is a tricky part. In normal scenario we need to communicate between client and server via string manipulation only. (Demo Code)
In this article we will discuss about, Microsoft Ajax and the way we can handle complex data types. We shall use web service for Ajax communication; web service will be exposed to client using Script Manager. Complex data types can be handled using JSON objects, in this article we will discuss only about how to handle complex data types. Script Manager internally uses JSON serialization class for handling complex data types; so will not care about the JSON about in this article.
Let’s assume we have a Public class Employee as below.




In above class the elements which we need to be accessed in JavaScript are public; here we are not considering any function in a class.

Again we are going to expose a web service to Script Manager for this article. So we also have a web service in demo code it is “WebService.asmx”.
Following two namespaces are required to make a web service Ajax Enabled. We will not go into any details of these namespaces.
using System.Web.Script.Services;
using System.Web.Script.Serialization;
Our web service class is as below





Following are the two extra things we have added above the WebService class, this is to indicate that the web service will be called from JavaScript, and is enabled of Creating corrosponding script object of class Employee.





In the Demo, Employee and WebService both classes are added under namespace Demo, and are in the same file “webservice.asmx”.
Our server side code ends here. Now we shall develop only client side code.
Our form tag is as follow




In above code, we have used script manganer and registred our web service and JavaScript file.
Here onwards we are going to deveolp JavaScript
Calling of WebService methods using JavaScript and script manager is very simple, we just need to use the simple namaspace sequence.
e.g. If we want to call getDefaultData function of a webservice we simply needs
Demo.WebService.getDefaultData().
If we want to add a response handler we just need to specify the function name in bracess like Demo.WebService.getDefaultData(OnSucceeded)
For the demo purpose our JavaScript contains mainly three functions

_getDefaultData() – This JavaScript function is used to call a webmethod getDefaultData. This Web Method returns default data Set for the Employee class.
The JS function is as below





_sendDataToServer() – This JavaScript function is used to pass client side input to the server, or to the web method.
The JS function is as below





IN ABOVE FUNCTION CHECK THE WAY WE HAVE CREATED OBJECT OF AN EMPLOYEE CLASS. THIS EMPLOYEE CLASS EXISTS IN C# CODE, BUT USING AJAX.NET WE ARE ABLE TO CREATE INSTANCE ON CLIENT SIDE AS WELL.

OnSucceeded(result,userContext, methodName) – This JavaScript function is used to Handle response from the server. The function is as below




Download Demo Code here ---> DealingWith_ComplexTypes.zip
Submit this story to DotNetKicks

Read more...

Get Direct HTML string for Server Side Control - Useful for Ajax Operations

How to get rendered HTML of any control for Ajax operations?
In ajax on client, what exactly we do is the simple manipulation of strings. Mainly we can use HTML strings and put it as innerHTML in desired tag (i.e. div,span,td, etc…).
Assume following sequence of operations
1. Send an Ajax request from client to server.
2. On server side we are binding data table to grid
3. Convert the grid into HTML string and send it back to client side.
4. On client side put that string as an innerHTML of desired tag.

Now to convert grid into HTML is a logical thing to develop, but in ASP.NET following code will generate HTML string of any control… This is a simple rendering of any control…
We will use one of the best feature of Asp.Net i.e. RenderControl.
Using this property of control we are able to get HTML of that control., but for this we will have to use HtmlTextWriter and StringWriter as follows
e.g.




Here result will contain HTML format of the grid control. We will convert grid control to HTML after binding the data.
Submit this story to DotNetKicks

Read more...

Thursday, July 1, 2010

Pop up window

To open new window we need to use following JavaScript function



This function allows us to open a new browser window for the viewer to use; all the attributes are separated by commas

Window Attributes

Below is a list of the attributes you can use:

1. width=300
Use this to define the width of the new window.

2. height=200
Use this to define the height of the new window.

3. resizable=yes or no
Use this to control whether or not you want the user to be able to resize the window.

4. scrollbars=yes or no
This lets you decide whether or not to have scrollbars on the window.

5. toolbar=yes or no
Whether or not the new window should have the browser navigation bar at the top (The back, foward, stop buttons..etc.).

6. location=yes or no
Whether or not you wish to show the location box with the current url (The place to type http://address).

7. directories=yes or no
Whether or not the window should show the extra buttons. (what's cool, personal buttons, etc...).

8. status=yes or no
Whether or not to show the window status bar at the bottom of the window.

9. menubar=yes or no
Whether or not to show the menus at the top of the window (File, Edit, etc...).

10. copyhistory=yes or no
Whether or not to copy the old browser window's history list to the new window.


Submit this story to DotNetKicks

Read more...