AJAX

February 25, 2008

How to make your web site work in all browsers

When we develop a web page with features which may not work in all browsers we need to ensure that the web page works with all browsers by programming the DOM elements. We do this by adding an event handler to an event exposed by a DOM element using $addhandler.

For those of you who are not familiar, a DOM element is a element of a DOM tree. A DOM tree is a hierarchical representation of all HTML elements which we place in the web page. An event handler helps to associate a function with an event. For example,

Object             Event Handler

Button              onclick
Text                onchange,  Onfocus

Note that this definition of event handler pertains to JavaScript.

Firstly, let us see how to attach code to Dom events using Javascript. If you use Javascript earlier, we will acquitted with the event model. We can program each DOM element of the DOM tree of a web page by associating events and code in event handlers as we will see below.

Let us take the example of a button. A HTML button element can raise a click event when it's clicked by the user. We will associate the function validcheck(), to the event handler onclick of the button object. The following code does this.

<input type=”button” name=cmdsubmit” onclick=” validcheck()>

A number of different types of event handlers can be triggered by different events.Common events that can trigger JavaScripts are mouse actions ,keyboard actions , actions on form fields.

This method of attaching code to DOM events will not work in all browsers. This is because, different browsers implement the DOM programming differently. So, your web page working on one browser may not work on other browsers.

The Microsoft Ajax Library provides to the problem by including an abstract API which abstracts the operations made on Dom elements. This API eliminates the need to know which functions are supported by the DOM implementation of a particular browser whether it is a Internet explorer, Firefox, Safari or Opera.

The abstraction API consists of two classes: Sys.UI.DomElement and Sys.UI.DomEvent.


Sys.UI.DomEvent Class
 

The Sys.UI.DomEvent Class is included in the Microsift Ajax library to provide cross browser compatibility to DOM events.  This class contains in the Namespace: Sys.UI. We use the DomEvent class to add, remove, modify, and handle client events.

Sys.UI.DomEvent addHandler Method
 

This method is a class of the Sys.UI.DomEvent and  enables us to add a DOM event handler to the DOM element.

Sys.UI.DomEvent.addHandler(element, eventName, handler);

Term              Definition

element          The element that exposes the event.
eventName     The name of the event.
handler           The client function that is called when the event occurs.

The class  Sys.UI.DomEvent addHandler can also be written as $addHandler.

Use the addHandler method to add a DOM event handler to the element that exposes the event. The eventName parameter should not include the "on" prefix. For example, specify "click" instead of "onclick". This method can be accessed through the $addHandler shortcut method.

$addHandler(element, eventName, handler);

The below example demonstrates how a blur event occurs when a text field on a form loses focus. This example also demonstrates the $addhandler will result in cross browser compatibility.

<form id="form1" runat="server">
<asp:ScriptManager ID="TheScriptManager" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function pageLoad() {
            var txtName = $get('txtName');                

            $addHandler(txtName,                              
               'blur', txtName_focus);                
        }

        function pageUnload() {
            $removeHandler($get('txtName'),                     
                'blur', txtName_focus);                
        }                                                         

        function txtName_focus(evt) { 
                      var count = $get("txtName").value.length;
                       $get("count").innerHTML="";
                       $get("count").innerHTML = count;

                                                                

        }

    </script>
    <span>Please type some text:</span>
    <input type="text" id="txtName" />                
    <span id="count">Number of characters</span>
    </form>

The above program displays the number of characters entered in the textbox when the textbox loses the focus.

February 22, 2008

Pros and cons of Programming models (AJAX)

Server Centric Programming Model

Compared to the client-centric programming model, the Server-centric programming model is easy to implement. All we need to know is develop the Asp.net application and then wrap certain areas of the page with UpdatePanels. By doing so, we will be using the minimal Ajax implementation.

Using UpdatePanels means posting the entire page to the server. Even when the required update to the web page is minimal, every asynchronous postback results in more server side processing. This results in downgraded performance.

From coding point of view, using UpdatePanel control results in elegant code. Sections of the page are wrapped by the UpdatePanels and all Ajax processing is taken up by the UpdatePanel control.

The server-centric approach denies granular level of control to the developer which is needed for sophisticated interactive web applications.

Client-Centric programming model

The Client-centric approach is adopted to build sophisticated interactive web applications. Such application scan be developed by using JavaScript, which means a high degree of expertise.

The Client-centric approach involves using ScriptManager control which enables calling of methods of a class bypassing the asp.net page life cycle. Which means, optimum usage of server resources.

Because we use client side DHTML controls, during a response, only required data from the server is rendered. This reduces the network traffic.

From a coding point of view, JavaScript code used for various features of a web page results in more maintenance.

The client-side approach has its own limitations as it cannot handle rich UI elements like menus, treeviews, grids, etc.




February 21, 2008

ASP.Net AJAX Programming models

When we set out to develop AJAX based web applications, we need to make a clear choice whether the application is going to be based on :

  • Server-centric programming model   
  • Client-centric programming model
  • Hybrid or a mixture of  Server-centric programming model and  Client-centric programming model

Many a times this decision is based on the existing applications which needs to be upgraded. Often factors like skills of a programmers available determine the choice of the programming model. Note that there are no clear guidelines which can help us to decide on the programming model. In this blog post we will see how a client-centric model and server-centric model is implemented.

Server-centric programming model

  • The application logic (written in VB.Net or C# )and user interface is hosted on the server.
  • This model is more like a minimal ajax implementation because we use only ScriptManager control, UpdatePanel control and almost no JavaScript code.
  • For existing applications to be upgraded to Ajax, we can retain the core Application logic and UI.
  • Flicker free increamental updates by using only the ScriptManager control, UpdatePanel control.

In the example below, we use the <UpdatePanel> tag and one of its child tags <ContentTemplate> to allow to refresh the label. By using the above tags, we are leveraging the power of Ajax to refresh the label without the need to postback the entire page.

The Server-Centric programming model involves adding the UpdatePanel control and placing all Asp.net controls within it. Note that in every Asp.net Ajax page, we need to place the one ScriptManger control.
The functionality of the below code is to increament the counter of the Label control when user clicks on the PartialButton.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode=Always ChildrenAsTriggers=true>
<ContentTemplate>
<asp:Button ID="PartialButton" runat="server" text="Partial Post Back" OnClick="InsideButton_OnClick" />
<br />
<br />
Counter (Partial):
<asp:Label ID="PartialLabel" Text="1" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
   
<script runat="server">

Sub InsideButton_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
  PartialLabel.Text += 1
End Sub
   
</script>

Client-centric programming model

The client-centric model is chosen when there is a compelling need to provide rich user experience in your application. In this programming model, both application logic and UI is implemented in the browser. The rich user experience is implemented using JavaScript, DHTML. Web service calls are used to retrieve the data from the server.

To learn more on creation of web services click here : Create a Web Service

So, the client-centric programming model requires a high level of Javascript expertise and atleast one team member should posses the knowledge of security issues of a web application.

In the example given below, we will add a new web service called myservice.asmx. this web service takes the string as input and returns the same. Note that in every client-centric application, a web service has to be used to retrieve the data from the server. As the given example is only for demonstration purposes, the input and returning value is the same and the example is straight forward. As the programs become sophisticated the input and return values will be varied.

In  the below code, we have used namespace System.Web.Script.Services namespace, which 
is part of the core ASP.NET AJAX framework.

Note that the two new attributes, [ScriptService],   [ScriptMethod]. The attribute [ScriptService] is the attribute of the class myservice and [ScriptMethod] is the attribute of the web method GetData(). These attributes are parsed by the ASP.NET AJAX framework and is used to determine what portions of the service are exposed in the JavaScript proxies.

Next we add a new web form called client-centricexample.aspx. the first step is to include ScriptManager control. Next, we declare a service reference to the local web service myService.asmx.  In the web form, we use two regular Html elements two textbox controls and one button. Whenever user clicks on the button in the page, the GetResult() javascript function is called. In this function we call the web service to display the text enetered by the user in another textbox control. In the statement, myService.GetData(document.form1.Text1.value,onComplete); 

The first  parameter is the data entered in the first textbox control and the second parameter is the name

of the callback function onComplete that is  called when the method returns succesfully. When the call return is completed, the changes to be made in the user interface is mentioned here.

In the statement document.form1.Text2.value = result; 

the control text2 is assigned the result of the web service. So, whenever user click the button, the textbox control is updated dynamically.

WebService/WebMethod code:

<%@ WebService Language="C#" Class="myService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myService : System.Web.Services.WebService
{

    [ScriptMethod]
    [WebMethod]

public string GetData(string myString)
    {
        return myString;
    }
}

HTML code:

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="myService.asmx" />
    </Services>
    </asp:ScriptManager>

<input type=text id=Text1 name=Text1 /> 
<input type=text id=Text2 name=Text2 />    
<input type=button id="btnGet" value="Getdata" onclick="GetResult();" />

JavaScript code:

<script type="text/javascript">

function GetResult()
{
      myService.GetData(document.form1.Text1.value,onComplete);
}

function onComplete(result)
{
    document.form1.Text2.value = result;
}

</script>
</form>

January 16, 2008

Javascript and .Net programmers

Why .Net programmers should learn Javascript.

With the introduction of AJAX, .Net programmers have to seriously consider learning JAVAScript to develop AJAX enabled applications.

ASP.NET AJAX is a framework for creating more efficient and interactive Web experiences that work across all the most popular browsers. Microsoft AJAX library is a Javascript library. Ajax is Free.

In the Web world, Javascript is the widely accepted language for developing powerful web applications with rich client side functionality and Microsoft has come out with its own version of Javascript libraries for developing web application. Microsoft has included the OOPs extensibility features into its Javascript library and chosen it as the language of choice for AJAX. Microsoft Javascript was originally called as Jscript.

It is obvious that to implement client side scripting we should learn JAVASCript.

Reasons why .Net programmers should consider Javascript:

  • Superior
  • No near competitor – Universal usage
  • Client side scripting is the technology of today

Superior

AJAX Javascript is superior than any version of JAVASCript because of the OOPs functionality incorporated to the JAVAScript library by MICROSOFT.

The Microsoft AJAX Library brings classic OOP concepts to JavaScript and adds namespace support for grouping functionality.

Features of AJAX Javascript are :

  1. Classes
  2. Namespaces
  3. Inheritance
  4. Interfaces
  5. Enumerations
  6. Reflection

No near competitor

Whether you use PHP or ASP for your server side application design, Javascript is the language of many to implement client side application development. Vbscript which was the original language of choice of Microsoft for implementing client side scripting is now promoting both Javascript (via AJAX) and VBScript. Due to its popularity and features Javascript is widely used. So, it becomes all the more important for .Net programmers to learn Javascript.

Client side scripting is the technology of today

Increased emphasis on User Interface and flicker free web pages have necessitated companies to find ways and means to come out with technologies, which provide these features.

We know that HTML is used to create client-side user-interfaces, but cannot handle client-side activities to respond to the user. The content of a Web application that consists of only HTML pages is static. It does not respond dynamically to the actions performed by users.

To respond to user requests, we can use both client-side and server-side scripting in addition to HTML pages. Note that a web application can have client-side scripting, server-side scripting or both.

The advantages of using client-side scripting is to program web pages that can dynamically respond to user input without having to interact with the web server. With scripting, we can check every keystroke of the user, without any server interaction.

For example, in a web application that requires users to enter a number before displaying a particular page, we need to ensure that a user does not leave the number textbox field blank. To check whether a user has left the number field blank, we write client-side scripts that execute on the client computer. A client-side-script scripting speeds up the response time of a web application. Scripting languages, such as VBScript and JavaScript are used to write client-side scripts.

Briefly:

  • JavaScript is a programming language that is used to make web pages interactive. It runs on your visitor's computer and so does not require constant downloads from your web site.
  • A script is a program or a sequence of instructions that is interpreted or carried out by another program rather than by the computer processor.
  • Java and Javascript are two completely different computer languages. Only their names are similar.
  • Running JavaScript is easy. JavaScript support is built right into web browsers. Provided that the visitors to your site are using web browsers that support JavaScript (most do) and have JavaScript enabled (it is by default) then your JavaScript will run.
  • JavaScript is an interpreted language and so no special program is required to be able to create usable code. Any plain text editor such as Notepad is quite satisfactory for being able to write Javascript.

Websites which you should visit:

For a quick detailed backgrounder on AJAX :
http://en.wikipedia.org/wiki/AJAX

Microsoft AJAX site. You will have to visit this site often !
http://www.asp.net/ajax/

For a quick tutorial on AJAX
http://www.w3schools.com/ajax/default.asp

A basic tutorial on AJAX you should not miss !
http://dhtmlnirvana.com/ajax/ajax_tutorial/



Twitter Updates

    follow me on Twitter
    AddThis Social Bookmark Button
    Blog powered by TypePad
    My Photo