Creating an ASP.NET AJAX-Enabled Grid using ICallbackEventHandler (Part 1)

This article details the development of an ASP.NET AJAX-enabled grid using ICallbackEventHandler, with operations which include sorting, paging and page length change. I will work through the code in sequence, but it may help to download to the entire code sample here

The basic features of the gird are as follows (All operations are asynchronous)

  1. Sort in ascending or in descending order by clicking on the arrows next to column name.
  2. Change current page.
  3. Change page length.

In this example we will use one of the most powerful features of ASP.Net – RenderControl.

Using this method we are able to access the HTML of a control. To do this we will have to also use HtmlTextWriter and  StringWriter as follows

e.g.

using (StringWriter sw = new StringWriter())

{

HtmlTextWriter htw = new HtmlTextWriter(sw);

_grid.RenderControl(htw);

htw.Flush();

string result = sw.ToString();

}

The result string will contain the HTML format of the grid control. We will now convert the grid control to HTML after binding the data.

We will start by developing the UI and code in following steps:

  1. Enter the following code in the <form> tag of the page to create a GridView and a Dropdownlist.

<div id=”Gridview” >

<asp:GridView EnableViewState=”false” runat=”server” id=”_grid” OnRowDataBound=”_grid_RowDataBound” AllowPaging=”True” >

</asp:GridView>

<br />

</div> Change page length to –

<asp:DropDownList ID=”ddl” runat=”server”>

</asp:DropDownList>

Please note that RowDataBound event of the grid has been activated.

  1. Now we will create a DataTable to be used as DataSource for the GridView.

public DataTable _sampleData

{

get {

DataTable dt = (DataTable)ViewState["DataTable"];

if(dt == null)

{

dt = new DataTable();

dt.Columns.Add(new DataColumn(“Contact Name”,typeof(string)));

dt.Columns.Add(new DataColumn(“Company Name”, typeof(string)));

dt.Columns.Add(new DataColumn(“City”, typeof(string)));

dt.Columns.Add(new DataColumn(“Country”, typeof(string)));

dt.Rows.Add(new object[] { “Maria Anders” ,”Alfreds Futterkiste”,”Berlin”,”Germany”});

dt.Rows.Add(new object[] { “Ana Trujillo” ,”Emparedados y helados “,”México D.F.”,”Mexico”});

dt.Rows.Add(new object[] { “Antonio Moreno”, “Antonio Moreno Taquería”, “México D.F.”,”Mexico” });

ViewState["DataTable"] = dt;

}

return dt;

}

In the above code we have used ViewState instead of a Session variable.

i.e.       ViewState["DataTable"] = dt;

This will preserve the table for that page. Using Session variable the table would be available throughout the website, but using ViewState the table will only be available for that page.

To bind this table to the GridView we simply use _grid.DataSource = _sampleData;

  1. We will write following four functions for grid operations
    1. We need four functions for ICallBackEventHandler – two are JavaScript functions (one for Callback to server and another for displaying the response data from server). And two are Server side functions (RaiseCallbackEvent(string eventArgument) and GetCallbackResult())
    1. Action .
    1. Page index of the Grid.
    1. Page size from the dropdown list (i.e. id is ‘ddl’).
    1. Add following code

      protected void Page_Load(object sender, EventArgs e)

    1. Now we will write code in the RowDataBound event of the GridView – i.e. in protected void _grid_RowDataBound(object sender, GridViewRowEventArgs e)
  • private void sortGrid(string Argument , string pageLength)

    {

    DataView dv = _sampleData.DefaultView;

    result = “”;

    dv.Sort = Argument;

    _grid.DataSource = dv;

    _grid.PageSize = Convert.ToInt16(pageLength);

    _grid.DataBind();

    renderGrid(_grid);

    }

    private void changePage(string Argument , string       pageLength)

    {

    result = “”;

    _grid.DataSource = _sampleData;

    _grid.PageSize = Convert.ToInt16(pageLength);

    _grid.PageIndex = Convert.ToInt16(Argument);

    _grid.DataBind();

    renderGrid(_grid);

    }

    private void changePageLength(string Argument,  string pageLength)

    {

    result = “”;

    _grid.DataSource = _sampleData;

    _grid.PageSize = Convert.ToInt16(Argument);

    _grid.DataBind();

    renderGrid(_grid);

    //pageLength is not used

    }

    private void renderGrid(GridView _grid)

    {

    using (StringWriter sw = new StringWriter())

    {

    HtmlTextWriter htw = new HtmlTextWriter(sw);

    _grid.RenderControl(htw);

    htw.Flush();

    lass=textCode>            result = sw.ToString();

    }

    }

    The names of the above functions indicates their functionality, the second parameter of the first three functions is “pageLength this is the value of the dropdown list

    JavaScript  functions are as follows:

    function UpdateGrid(args)

    {

    args = args + “$” + window.document.getElementById(‘ddl’).value;

    <%= ClientScript.GetCallbackEventReference(this,”args”, “ShowResult”, null) %>

    }

    After rendering, if we open the source of the page; above function will appear as

    function UpdateGrid(args)

    {

    args = args + “$” +            window.document.getElementById(‘ddl’).value;

    WebForm_DoCallback(‘__Page’,args,ShowResult,null,null,false)

    }

    When we want to do a Callback, we are actually firing an event which is related to the Webform. Therefore the UpdateGrid(args) function needs to be placed in the <form> tag, otherwise we will get a JavaScript error.

    We register this function by using Page.ClientScript.RegisterClientScriptBlock so the function will appear in <form></form> tag only.

    function ShowResult(eventArgument,context)

    {

    window.document.getElementById(‘Gridview’).innerHTML = eventArgument;

    }

    This function will be fired after server sends a response back to client, thus this function will handle the server response. We have simply put the response as innerHTML of the Div tag. The innerHTML contains the HTML of the updated grid.

    The server-Side functions are as follows

    public string GetCallbackResult()

    {

    return result;

    }

    This function simply returns the result which we have put as innerHTML in the ShowResult function.

    public void RaiseCallbackEvent(string eventArgument)

    {

    string[] args = eventArgument.Split(‘$’);

    if (args[0] == “sort”) { sortGrid(args[1], args[2]); }

    else if (args[0] == “changePage”) { changePage(args[1], args[2]); }

    else if (args[0] == “changePageLength”) { changePageLength(args[1], args[2]); }

    }

    In this function the eventArgument will appear as “changePage$1$10” or “sort$1$10” or  “changePageLength$1$10” or “sort$Contact Name Asc$10” or  “sort$Contact Name Desc$10” in the rendered page

    If we split this on “$”, we will get

    (In changePageLength we don’t need args[2]; I have kept is just to simplify the code)

    In RaiseCallbackEvent we have called the function which we have decleared in POINT 3, each function in point 3 will do the respective action and return a HTML string of the Grid.

    if (!IsPostBack)

    {

    _grid.DataSource = _sampleData;

    _grid.DataBind();

    ddl.Items.Add(“10″);

    ddl.Items.Add(“20″);

    ddl.Items.Add(“30″);

    ddl.Attributes.Add(“onchange”, “javascript:UpdateGrid(‘changePageLength$’ + this.value);”);

    }

    [At this point if we compile the code we will able to chage the page  length ]

    //break//

    For adding the columnwise sorting functionality in grid, we will modify columnheader row of the GridView. 

    if (e.Row.RowType == DataControlRowType.Header)

    {

    for (int i = 0; i < e.Row.Cells.Count; i++)

    {

    e.Row.Cells[i].Text = string.Format(“{0}<img alt=”Ascending” src=”Images/up.jpg” onclick=”UpdateGrid(‘sort${0} Asc’)”; /><img alt=”Descending” src=”Images/down.jpg” onclick=”UpdateGrid(‘sort${0} desc’) “; />”, e.Row.Cells[i].Text);

    }

    }

    We have added up and down images and an onclick event of either of them will call the UpdateGrid function (Ref. Point 4) for sorting  Ascending and Descending order repectively. [At this point you can complie the code and the grid will be sortable].

    After this we will modify the Pager row in such a way that we can use it to change the page index of the grid using UpdateGrid function.(Ref. point 4 public void RaiseCallbackEvent)

    else if (e.Row.RowType == DataControlRowType.Pager)

    {

    GridView gdv = (GridView)sender;

    int _pageCount = gdv.PageCount;

    e.Row.Cells[0].Text = “”;

    for (int i = 0; i < _pageCount; i++)

    {

    HyperLink hyp = new HyperLink();

    hyp.Text = i.ToString() + “&nbsp;”;

    hyp.Attributes.Add(“href”, “javascript:UpdateGrid(‘changePage$” + i + “‘);”);

    e.Row.Cells[0].Controls.Add(hyp);

    extCode>         Label l = new Label();

    l.Text = “&nbsp;”;

    e.Row.Cells[0].Controls.Add(l);

    hyp = null;

    }

    }

    _pageCount contains the pagecount of the GridView. We have to display pages as Numbers so we used a HyperLink and a Label to add space after each page number.

    Finally, we can set EnableViewState=”false” this will not affect the functionality but the extra code of the ViewState will not come on client side which leads to lighter page.

    The entire code for the sample can be downloaded here

Posted in Articles | Leave a comment

Getting started with AJAX using PHP : Tutorial

AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms.

In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is not a programming language, so you don’t have to learn any new technology. AJAX can be implemented by using existing standards (JavaScript and XML) in a different way.

If we are using PHP or any server side technology and need to extract data from storage on a server (eg a database or a file), we will have to make an HTTP request (either POST or GET) to get the data. Once the data is received the the web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from server in background and then display it on the page without a reload. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object (XML over HTTP). With an HTTP request, a web page can make a request to, and get a response from a web server without reloading the page.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. But the creation of XMLHttpRequest object is different in Internet Explorer than the other browsers. I will discuss this later. To use AJAX to request a data from the server we need to do the following.

1. Create an XMLHttpRequest object.
2. Then using this object, request data from the server.
3. JavaScript will then monitor for the changing of state of the request.
4. If the response is successful, then the content from the data store requested will be returned as response (response can be in the form of a String or XML).
5. Use the response in your web page.

1. Create an XMLHttpRequest object

JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object. The following codes creates an XMLHttpRequest for all browsers:

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5
req = new ActiveXObject(“Microsoft.XMLHTTP”);
} else if(window.ActiveXObject){
//For IE 6+
req = new ActiveXObject(“Msxml2.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject(“Microsoft.XMLHTTP”) and for IE 6.0+ use new ActiveXObject(“Msxml2.XMLHTTP”). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.

var req;
try
{
// Firefox, Opera, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
}
}

In JavaScript, if statements within a try section fail, then the execution resumes from the corresponding catch block. Here first we are trying to get create a XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject(“Msxml2.XMLHTTP”), and if it fails also we will try ActiveXObject(“Microsoft.XMLHTTP”). If all these fail, then we will alert the user that his/her browser does not support AJAX.

2. Request for a web page

After creating the XMLHttpRequest we now need to send the web request using the open method. We also need to specify the HttpRequest method, GET or POST. Use the following code to send the request.

req.open(“GET”,”somedata.php”);
req.send(null);

Here, req is the XMLHttpRequest object. It will request to the server for somedata.php using GET method. The open function also has a third parameter, an optional boolean parameter. You should set that to true :

req.open(“GET”,”somedata.php”,true);
req.send(null);

Both of the above is correct.

3. Monitor for the response of the request

You will need to monitor for the state of the request. For doing this you can assign a function to req.onreadystatechange (Here, req is the XMLHttpRequest object), like below.

req.onreadystatechange=function()
{
if(req.readyState==4 && req.status == 200)
{
var resp = req.responseText;
}
}

Or like this,

req.onreadystatechange = handleResponse;

function handleResponse(){
if(req.readyState == 4 && req.status == 200){
//returned text from the PHP script
var response = req.responseText;
}
}

The readyState property holds the status of the server’s response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.

//break//

4. Get the response

The response will be as string or as XML. The data sent back from the server can be retrieved with the responseText property as string. Use responseXML for getting the response as XML.

5. Use the response on your web page

You can use the response you got from the XMLHttpRequest in your web page/application. You can either set a value of a text field or use the returned HTML from the web request as innerHTML for a <div></div> tag or <span></span> tag (See below for the implementation of this)

Using AJAX with PHP

I usually place all the AJAX related functions in one JavaScript (ajax.js), and later add the JavaScript in my PHP pages. My ajax.js looks like below.

function createRequestObject(){

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}

function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(“ajax_res”).innerHTML = response;
}
}
}

Now I add a <script></script> tag in my PHP pages like following to access the JavaScript functions.

Then I create a function called sendReq() as shown
above for preparing the URL to the PHP page to get some data from the database. If you look into the ajax.js, you will see that I’m assigning the output of the PHP page to a <div> tags innerHTML. My div tag has the id=’ajax_res’.

<div align=”center” class=”black” id=”ajax_res”>
<img src=”wt_bg.jpg”>
</div>

After calling the sendReq function with a value of ‘success’, it will connect to the server for sending a request to the URL get_lcm.php?status=success, then get the data from the database using the value ‘success’, and set the innerHTML attribute of the div tag whose id is ‘ajax_res’ according to the response. Initially my div tag shows an image, but after AJAX responds successfully this image will be replaced with the response. You can also get the response as the value of an input text.

My get_lcm.php looks like this.

<?php
include_once(“create_table.php”);

if(!empty($status)){
echo “<strong>Search Result for Status: “.$status.”</strong><br><br>”;

$ct = new createtable(“select * from lcm where state=$status”);

$ct->table_viewer();
}
?>

I used one of my PHP classes ‘create_table.php’ for creating a table from SQL queries. ‘create_table.php’ has a function, table_viewer(), to print the SQL output as a HTML table. I will discuss about this class and some other data abstraction classes I used in some later articles, if necessary.

I had the following HTML code for calling the AJAX function using the sendReq() as described earlier.

<a class=”none” href=”#” onClick=”sendReq(1)”>ACTIVE</a>

If a user clicks the above hyperlink, then the JavaScript function sendReq is invoked using the value of status equal to 1. After that the webpage with URL get_lcm.php?status=1 will be invoked. This PHP will get the information from database and shows the result as table. This result will then be displayed within the <div> tag.

Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development is you place all your AJAX related code in a single JavaScript file and reference it from anywhere you need AJAX.

There is another way of getting the same result from PHP without using the XMLHttpRequest object. But I personally do not like the concept, because it is missing one of the main ingredients of Asynchronous JavaScript And XML (AJAX), XML. This concept is good for the old browsers with no supports for XMLHttpRequest object, but as all the newer versions are supporting XMLHttpRequest object you can use AJAX for the common browsers.

PHP Tutorial has more PHP AJAX Tutorials.

Posted in Articles | Leave a comment

Using ICALLBACKEventHandler in ASP.NET

About ICallbackEventHandler:

ASP.NET 2.0 introduced an interface named ICallbackEventHandler (System.Web.UI.ICallbackEventHandler) to allow asynchronous communication with the server. Unlike Postback, in Callback only user defined information is sent to the server. Instead of using Postback to post the page, ICallbackEventHandler uses the DoCallback event to send user defined data to server, and return a String to client; on the client-side JavaScript can then manipulate the string. In total we have to use four functions for the implementating ICallbackEventHandler; two client side functions (in javascript) and two server side functions (C# in this case).


Use of ICallbackEventHandler:

To use ICallbackEventHandler, we will need to inherit it on the page or in a user control. The code will for this will be:

public partial class Default2 : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler

As a result of inheriting from ICallbackEventHandler, we have to implement two functions, namely:

  • public void RaiseCallbackEvent(String eventArgument)
  • public String GetCallbackResult()

As name of the above two functions indicates, the first function gets called automatically whenever there is a CallbackEvent. After the first function the second function i.e. GetCallbackResult gets called and returns a string to the client

So how to raise a CallbackEvent? For this we will have to use javascript. There will be two javascript functions:

  1. A function which will call RaiseCallbackEvent.
  2. A function which will handle the response from the server. This function will be called automatically after GetCallbackResult() and the string returned by GetCallbackResult will appear in JavaScript as input to this function.

Implementing ICallbackEventHandler

1. Create an ASPX page as follows

<body>
<form id=”form1″ runat=”server”>
<div>
Select The Item and Click the Button
<asp:DropDownList ID=”DropDownList1″ runat=”server”></asp:DropDownList>
<br />
<br />
<button type=”Button” onclick=”CheckForTimeZone()”>Get Timezone</button>
<br />
<table><tr>
<td>GMT Time zone is :</td>
<td><div id=”Results” runat=”server”></div></td>
</tr></table>
<br />
</div>
</form>
</body>

In above code “CheckForTimeZone()” in the button tag is a javascript function which we will add later. Also note that the button is a simple HTML control.

2. JavaScript in the Aspx page.

  <script type=”text/ecmascript”>

    function CheckForTimeZone()
{
var lb = document.getElementById(“DropDownList1″);
var selectedItem = lb.options[lb.selectedIndex].text;
CallServer(selectedItem, “”);
}

function ReceiveServerData(retValue)
{  
document.getElementById(“Results”).innerHTML = retValue;
}

  </script>

In above code  CallServer(selectedItem, “”) will be responsible for calling RaiseCallbackEvent on server side. And the ReceiveServerData(retValue) function gets called by GetCallbackResult().
To make above code work the way we want; we will need to add some code to the aspx.cs file.

//break//

3. Server-Side C# code (i.e. apsx.cs file)

public partial class Default2 : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
private static Hashtable hashTable;
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String cbReference =
Page.ClientScript.GetCallbackEventReference(this, “arg”, “ReceiveServerData”, “context”);
String callbackScript;
callbackScript = “function CallServer(arg, context)” +
“{ ” + cbReference + “;}”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“CallServer”, callbackScript, true);

            hashTable = new Hashtable();
hashTable.Add(“Hawaii”, “GMT -10:00″);
hashTable.Add(“Central America”, “GMT -06:00″);
hashTable.Add(“Greenland”, “GMT -03:00″);
hashTable.Add(“Athens”, “GMT +02:00″);

            DropDownList1.DataSource = hashTable;
DropDownList1.DataTextField = “key”; //If you say value Values from HashTable will be added to Drpdownlist
DropDownList1.DataBind();
}
}

In the above code, please note the following:

String cbReference =   Page.ClientScript.GetCallbackEventReference(this, “arg”, “ReceiveServerData”, “context”);
If we debug the code “cbReference” it will contain “WebForm_DoCallback(‘__Page’,arg,ReceiveServerData,context,null,false)
”; . Observe that the string, WebForm_DoCallback contains ReceiveServerData, it’s the javascript function we have written in step 2.

String callbackScript;
callbackScript = “function CallServer(arg, context)” + “{ ” + cbReference + “;}”;

Again “callbackScript” will contain some string. Actually it is a JavaScript function which we will register to the client page. Using

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),”CallServer”, callbackScript, true);
This registers our CallServer function on the page. We are essentially passing the selected item of the Dropdown list to the CallServer function if you see the source code of the output page the CallServer function will appear as follows:

<script type=”text/javascript”>
<!–
function CallServer(arg, context){ WebForm_DoCallback(‘__Page’,arg,ReceiveServerData,context,null,false);}// –>
</script>

This CallServer function is responsible for raising the callbackEvent ( i.e. RaiseCallbackEvent(String eventArgument) ) and the “arg” will be the eventArgument.

4. Finally add RaisecallbackEvent and GetCallbackResult.

Add following code to aspx.cs file
public void RaiseCallbackEvent(String eventArgument)
{
if (hashTable[eventArgument] == null)
{
returnValue = “-1″;
}
else
{
returnValue = hashTable[eventArgument].ToString();
}
}
public String GetCallbackResult()
{
return returnValue;
}

The above code provides the basic plumbing to implement asynchronous callbacks using ICALLBACKEventHandler. In subsequent articles we will extend this to real world applications and develop an AJAX-enabled GridView control.

Posted in Articles | Leave a comment

Introducing Asynchronous Java Script and XML (Ajax) in ASP.NET

One of the most important challenges web application developers face is the requirement for a fast and responsive user interface.  AJAX was primary designed and developed with the intent of providing a fast and responsive user interface to address these challenges. According to Enrich Peterson, “AJAX-enabled pages provide a slick, responsive user experience, making web-based applications function more like desktop-based ones”.

 

This article guides the reader through this new technology, its features, benefits and applicability in web application development. This is the first in the series of articles on Ajax (and more specifically ASP.NET AJAX). Although Ajax is independent of the technology with which it is implemented (you can implement Ajax enabled web applications using Java, Microsoft .NET or many other programming models), I will discuss implementation of Ajax in ASP.NET, how we can consume Web Services using AJAX, etc, in this series.

 

 

Why AJAX?

 

The primary advantages of using Ajax in web application development are as follows.

 

Ø  Reduction of unnecessary web server hits, i.e., the round trips are minimized

Ø  Rich, responsive user interface

Ø  Real-time web page updates

Ø  Language neutrality

Ø  Faster web page renderings

Ø  Less consumption of server’s resources (memory and processor load is reduced)

 

In the Ajax enabled web applications, requests are sent to the server only for the data that is needed. The entire web page is not submitted at one go.

Ajax makes use of XML, XSLT, XMLHttpRequest, JavaScript, HTML, and DHTML.

 

How does <
st1:City w:st="on">AJAX work?

 

Let us start by defining what AJAX is. AJAX, an acronym for Asynchronous JavaScript and XML, is a cross-platform technology that can be used to make your web pages fast, rich and responsive.

The key to the success of AJAX lies in the way it works. “Asynchronous” as it is called, implies that in the earlier days, the web applications used to be synchronous. This reminds me of the term “serial multi-tasking”, the type of multi-tasking the DOS Operating System used to support. A synchronous nature of execution implies that until and unless a request is complete in all respects, another cannot start. In other words, the requests have to be executed one after the other.

 

The AJAX engine runs within the context of the web browser using JavaScript and DOM technologies. In AJAX, the JavaScript that is loaded at the time when the web page loads is responsible for handling the basic tasks of data validation, changes to the data, etc; while the data transfer that happens from the user interface to the database and vice-versa, continues to happen in the background, i.e., it is independent of the other operation that we just mentioned about. This is what is known as “Asynchronous” mode of execution.

 

In an Ajax enabled web application, the runtime loads the Ajax engine instead of loading a webpage at the beginning. This engine is responsible for both rendering the data for  the user interface and also communicating with the web server for transporting data back and forth. “The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server.”

 

Ajax is a mainly a mix of Javascript,Html, CSS, XML, DOM and the XMLHttpRequest Object. Ajax helps us to avoid reloading the web page as and when a specific portion of the web page changes due to user inter actions. Using Ajax, you can dynamically retrieve data from the application running in the context of the web server whenever a user interaction happens using the XMLHTTPRequest object. But, what is this XMLHTTPRequest object? Today’s browsers contain the XMLHttpRequest object that can be used to create a GET or POST request asynchronously. It also helps us to register a callback method that is invoked when the resposne for that request returns to the client side browser. This response can in turn be either in plain text or in XML format. In the former case, we can simply display the response in the web browser; in the later, you require parsing the XML prior to displaying in the browser. Note that the XMLHttpRequest Object is one of the major components of the Ajax framework and facilitates asynchronous processing and also supports events. 

 

AJAX and ASP.NET

 

Microsoft introduced support for AJAX in ASP.NET in the form of a separate add-on called ASP.NET 2.0 AJAX Extensions, an extension of ASP.NET that is totally integrated with the server-based services and helps you to design and implement Ajax enabled web applications using ASP.NET technology. It actually is comprised of a set of technologies that enable AJAX support in the ASP.NET environment. According to MSDN, “ASP.NET AJAX is a set of technologies to add AJAX (Asynchronous JavaScript and XML) support to ASP.NET. It consists of a client-side script framework, server controls, and more”. “Although AJAX is essentially a client-side technique, most of its real-world deployments call for server-side processing.”

 

The ASP.NET 2.0 framework incorporates the client script libraries of the ASP.NET Ajax framework. Note that ASP.NET AJAX is an extension of the ASP.NET server-based development framework. You can use ASP.NET AJAX to build web applications with rich user interface and improved response times. “The framework includes two distinct yet not mutually exclusive API’s: client and server, which enable the developers to accomplish AJAX functionalities using direct client-side programming, traditional server-side programm
ing, or any combination of both”.

 

Available ASP.NET Ajax Frameworks

 

These are several of Ajax frameworks for ASP.NET that you can choose from. The following are some of the best Ajax frameworks.

 

Ajax.NET Professional

ASP.NET AJAX from Microsoft

Ajax.NET

MajicAjax.NET

 

The ASP.NET AJAX Control Toolkit

 

The ASP.NET AJAX Control Toolkit from Microsoft is a community project that comprises of a SDK and code samples. According to Microsoft, “The ASP.NET AJAX Control Toolkit provides a set of sample controls and extenders that makes it a snap to spice up your web site with rich functionality”.

 

You can download the Ajax Control Toolkit from the following link:

http://www.codeplex.com/AtlasControlToolkit/Release/ProjectReleases.aspx

 

Suggested Readings

 

http://www.ajaxtoday.com/ArticleDetail/tabid/62/ArticleID/45/Default.aspx

http://www.developerfusion.co.uk/show/4704/

http://aspnet.4guysfromrolla.com/articles/062106-1.aspx

http://www.codeproject.com/Ajax/IntroAjaxASPNET.asp

 

AJAX Downloads and Resources

 

You can download AJAX from the following link. This is the official link for ASP.NET AJAX resources. http://ajax.asp.net/downloads/

 

Conclusion

 

Asynchronous JavaScript and XML, or ace w:st="on">AJAX is a technology that can be used to send and receive data (usually in XML format) from a server-side application using

Javascript. AJAX has introduced radical changes in how web applications are developed these days. You can use ASP.NET AJAX to enrich the user interface of your web applications seamlessly and ensure that the user interface is fast and responsive with less resource overheads involved for rendering of data from the web server to the web clients. The forthcoming articles in this series of articles on Ajax would discuss more and more on Ajax and how we can build and implement Ajax in ASP.NET applications. So, stay tuned!

Posted in Articles | Leave a comment

AjaxTags Tutorial (Part 2)

Creating an Autocomplete Textbox

One of the cool tags of AjaxTags is ajax:autocomplete. We will use this tag in this following JSP example.

<fieldset>
<legend>ajax:autocomplete example</legend>
<form>
<label for=”country”>Country Name: </label>
<input type=”text” name=”country” id=”country”/>
</form>

<ajax:autocomplete
source=”country”
target=”country”
baseUrl=”country_list.view”
parameters=”country={country}”
className=”autocomplete”
minimumCharacters=”1″/>
</fieldset>

Our objective here is to make an autocomplete for the textbox country. We have a Servlet which will return a list of country names that starts with the value of country textbox.
This tag must appear after the form tag. Attribute source is the id of the input textbox. Attribute target is the id of the target textbox; target may be same as source or different than source. Attribute baseUrl specifies the server side code. One important attribute for ajax:autocomplete is minimumCharacters, it specifies character count after which AjaxTags will request for country_list.view with country name as a parameter.

.autocomplete {
position: absolute;
color: #333333;
background-color: #ffffff;
border: 1px solid #666666;
font-family: Arial;
overflow: hidden;
}

This is a sample style sheets entry for ajax:autocomplete.

Now we need to create the server response for this tag. Sample response would be like following. Assuming we entered ‘A’ in country textbox.

<?xml version=”1.0″ encoding=”UTF-8″?>
<ajax-response>
<response>
<item>
<name>America</name>
<value>America</value>
</item>
<item>
<name>Angola</name>
<value>Angola</value>
</item>
<item>
<name>Austria</name>
<value>Austria</value>
</item>
<item>
<name>Australia</name>
<value>Australia</value>
</item>
</response>
</ajax-response>

In Part I, I discussed AjaxTags helper classes. First we need to add following import statements in your Servlet code.

import org.ajaxtags.helpers.*;
import org.ajaxtags.servlets.*;

Next you need to extend your class from BaseAjaxServlet.

public class CountryCompleter extends BaseAjaxServlet

BaseAjaxServlet is included in ajaxtags.jar.

We define a string of country names that will be used for autocomplete source.

private static final String countries = “America,Angola,Austria,Australia,Bahama,Bangladesh,Bermuda,Canada,Chad,
Cyprus,Denmark”;

We will spilt this string using “,” as separator into an array.

private static final String[] countryNames = countries.split(“,”);

We need to override getXmlContent function to generate XML response. Here is an example.

public String getXmlContent(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
//Gets country prefix from request object
String countryPrefix = request.getParameter(“country”);

//Generate country names’ list as XML
String countryList = makeCountryList(countryPrefix);

//Returns XML list as string
return countryList;
}

Now we need to develop a private class named makeCountryList for generating XML response with all the country names starts with the country prefix as entered by the user.

private String makeCountryList (String countryPrefix) {
AjaxXmlBuilder builder = new AjaxXmlBuilder();
for(String country: countryNames) {
if(country.toUpperCase().startsWith
(countryPrefix.toUpperCase())) {
builder.addItem(country, country);
}
}
return builder.toString();
}

Compile the class. Add entries in your web.xml. First a Servlet entry like below.

<servlet>
<servlet-name>CountryCompleter</servlet-name>
<servlet-class>CountryCompleter</servlet-class>
</servlet>

Then add a Servlet mapping entry in web.xml.

<servlet-mapping>
<servlet-name>CountryCompleter</servlet-name>
<url-pattern>/country_list.view</url-pattern>
</servlet-mapping>

You now have everything ready for this example. Try for yourself and you will learn how to use ajax:autocomplete tag.

//break//

This server side code in some cases may take too much time. In such instances you can show an indicator or progress bar while processing. To do this you need to set the indicator attribute of ajax:autocomplete. The Indicator attribute usually points to a div or span element that will be enabled while the results are being loaded. It is disabled at start, and disabled again when results come back. The div or span element usually contains an animated GIF showing progress like progress bar.

<fieldset>
<legend>Autocomplete with indicator</legend>
<form>
<label for=”country”>Country Name:</label>
<input type=”text” name=”country” id=”country”/>
<span id=”indicatorRegion” style=”display:none;”>
<img src=”images/progress_bar.gif”/>
Loading…
</span>
</form>

<ajax:autocomplete
source=”country”
target=”country”
baseUrl=”country_list.view”
className=”autocomplete”
minimumCharacters=”1″
indicator=”indicatorRegion”/>
</fieldset>

 

Creating Cascading Drop Downs

Using AjaxTags you can create cascading drop downs (when first one changes, result is sent to server and used to compute values for second) easily. This can be done using ajax:select tag.


<fieldset>

<legend>ajax:select example</legend>

<form>
<label for=”make”>Make:</label>
<select id=”make”>
<option value=”">Select Make</option>
<option value=”Nokia”>Nokia</option>
<option value=”SonyEricsson”>SonyEricsson</option>
<option value=”BenQ”>BenQ</option>
<option value=”O2″>O2</option>
<option value=”Motorola”>Motorola</option>
<option value=”Apple”>Apple</option>
<option value=”HTC”>HTC</option>
</select>
<label for=”model”>Model:</label>
<select id=”model” disabled=”disabled”>
<option value=”">Select Model</option>
</select>
</form>

<ajax:select
source=”make”
target=”model”
baseUrl=”model-finder.ajax”
parameters=”make={make}” />
</fieldset>

Here you can see two drop down elements, one is make and other is model. If you select anything from make then corresponding models will be loaded to model drop down. Remember, you must add a dummy option at the beginning. Ajax requests will be triggered after select value changes. So, you need the dummy option. 2nd Select element is disabled at beginning. If first select value changes, AjaxTags will request for server response and populate second select accordingly. This tag must appear after form tag. All the tags those require id values in source and target must appear after form tag.

 

htmlContent Tag

Ajax:htmlContent must be placed below form. When some source element (like button) clicked, server-side resource is invoked and return values placed inside html area (usually a div or span). Attribute source is the id
of the button or other element that will trigger submission. Attribute target is the id of the html element where results from server will go. Server side resource should return regular HTML, not XML. Here is an example of single trigger.

<fieldset>
<form>
<label for=”make”>Make:</label>
<select id=”make”>
<option value=”">Select Make</option>
<option value=”Nokia”>Nokia</option>
<option value=”SonyEricsson”>SonyEricsson</option>
<option value=”BenQ”>BenQ</option>
<option value=”O2″>O2</option>
<option value=”Motorola”>Motorola</option>
<option value=”Apple”>Apple</option>
<option value=”HTC”>HTC</option>
</select>
<label for=”model”>Model:</label>
<select id=”model” disabled=”disabled”>
<option value=”">Select Model</option>
</select>
<input type=button id=showprice value=”SHOW PRICE”>
<span id=”price”></span>
</form>

<ajax:select
source=”make”
target=”model”
baseUrl=”model-finder.ajax”
parameters=”make={make}” />
<ajax:htmlContent
baseUrl=”price-finder.ajax”
source=”showprice”
target=”price”
parameters=”model={model},make={make}”/>
</fieldset>

Here showprice is used for single trigger. We can use multiple triggers for ajax:htmlContent. To do this we need to remove source attribute and add sourceClass attribute. Value of sourceClass is the CSS class of an element. All the elements that have a CSS class name same as sourceClass can be used for trigger. Example of multiple triggers is below.

<form>

<input type=”button” value=”Show Price” class=”trigger”/>
<a href=”javascript://no-op” class=”trigger”>Show Price</a>
<input type=”radio” class=”trigger”/>Show Price

<span id=”price”></span>
</form>

<ajax:htmlContent
baseUrl=”price-finder.ajax”
sourceClass=”trigger”
target=”price”
parameters=”model={model},make={make}”/>

The other tags are –

ajax:area
Defines a region and forces all links to be loaded back inside same region instead of refreshing the entire page.

ajax:callout
The callout tag associates a callout or popup balloon to any HTML element supporting an onClick event. AjaxTags uses OverLIBMWS JavaScript library for ajax:callout tags.

ajax:displayTag
The displayTag is similar to the area tag. Allow pagination and sorting.

ajax:portlet
It defines a portion of the page that expects content from another location using Ajax with or without a periodic refresh.

ajax:toggle
The toggle tag uses a single image to represent the display of the ratings with the help of CSS to manage the mouseover or mouseout.

ajax:tree
Generate JavaScript code to build a tree.

For more information about the attributes and parser please go to AjaxTags usage page at http://ajaxtags.sourceforge.net/usage.html. You will also find all the necessary JavaScript libraries, demo war files and CSS style sheets in AjaxTags download pages.

Posted in Articles | Leave a comment

Introduction to the Dojo Toolkit : Tutorial

This article is geared towards people with some javascript knowledge, that might have used another ajax/js framework before, but now have a really pressing need to use some of the features found in dojo.

So, what is it really?

Dojo is quite a lot of things. It has a staggering amount of widgets, to begin with; Dialogs, Panes, Menus, WYSIWYG editors, Buttons, Color pickers, Clocks, Layout Managers and a host of other things- just in the widgets department. Then there’s the very handy encryption package, handy for hashing things coming to and from the server-side, the Drag-n-Drop package which works with nearly any element on the page, the essential Collections API with Java-like iterators and whatnot, and of course the powerful  proper Ajax functionality with several bells and whistles of its own.

Apart from the sheer amount of functionality available in dojo, there are a few architectural differences compared to most other frameworks; Dojo uses namespaces. This means that dojo always includes the package names in an object reference. If I want use the very nice for-each loop function, for instance, I have to refer to is like this; “dojo.lang.forEach(listOfThings, myFunc);”, instead of just “forEach(listOfThings, myFunc);”.

It seems to be a lot of trouble and waste a lot of space, but in reality it’s not a big change and it increases readability when debugging or refactoring things later. Another example is that when you want to refer to a DOM element the “dojo way”, you write “dojo.byId(el.id);” instead of prototypes inarguably more compact “$(el.id);”  Another big change in philosophy between dojo and prototype is that prototype has a long and glorious history of changing basic javascript objects, such as adding useful new functions to the string object.

This has resulted in collisions or erratic behavior when using other javascript libraries which want to change or assume a certain functionality of the very same function names. By using namespaces, dojo ensures that no collisions occur between itself and any other libraries on the same page.

I’m going to use the dojo API version 0.4.2 in the examples, since the upcoming 0.9 only has reached milestone 2 as of this writing.

Getting the right stuff and copying the right files to your server

    You might think that using a javascript-based framework should be dead simple. In many cases it is, but due to de facto standards set up by many smaller frameworks (or libraries),         some design choices in dojo requires reading some of the fine print – or reading this article :) . The most important thing to remember is that dojo is more that just the file dojo.js. It is     not uncommon for people starting to use dojo to assume that the src/ directory really isn’t needed, and probably is shipped only as a kind of open source service to the developer.

    However, when you download and unzip the “standard” dojo package (dojo 0.4.2-ajax), the dojo.js file is only the starting point, the kernel so to speak, of dojo. All real functionality     exists – and exists only - in files under the src/ directory. Also, most widgets have a lot of template html files and images that they have to get at, so the short dance version of this     point is; Copy everything.

Check the test to see how things are done

    The biggest problem the dojo community faces (IMHO) is the lack of a thorough API documentation and walk-through examples. True, there’s a very useful (at least to the                 intermediate-level dojo hacker) API tool, and there are several good sites which give fairly up-to-date walk-throughs and examples in specific areas. But the really good bits can be     found on the test directory which also ships with the standard package.

    If you go to http://download.dojotoolkit.org/release-0.4.2/dojo-0.4.2p1-widget you’ll see two interesting directories; demo and tests. The reason I refer to the live URL at the dojo             download site is that you might want to poke around at other (upcoming) versions. The demo directory contains a fair number of demos, which are neatly organized in the following     sections; Demo Applications (Mail client, Text editor), Effects (Fades, Wipes, Slides, et.c.), Drag and Drop, Storage, RPC, Layout Widgets, Form Widgets and General Widgets (Buttons, Menus, Fisheye menus, Tooltips, et.c.). This is a good place to let your jaw drop a bit and get some inspiration.

    But the really good stuff is found under the tests directory. Here you will find unit tests for almost all widgets, layout containers, graphics, and lots of other things you’ll find truly         useful. The reason the tests are more useful is that they are short, focussed and sometimes even (drumrolll, please) commented! My recommendation is to check out tests/widget for     test_ModalFloatingPane, test_Dialog and test_Menu2_Node for some basic examples on how to use dojo widgets. Although dojo is an Ajax framework, much of the truly sterling functionality it  offers has little if anything to do with client-sever communication – as you will find out.
//break//
Your first dojo-page

    Before you do the fancy stuff you’re surely shaking with barely controlled desire to do, it’s a good idea to get a minimal “template-page” up and running. Of course, you could just grab one of the tests files and change things about, but how fun would that be? Here is a minimal html-page to start with, happily snarfed from one of the Dialog tests and shortened a bit;

    <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
    <html>
        <head>
            <title>My first Dojo page</title>
                 <script type=”text/javascript” src=”dojo.js”></script>
                 <script type=”text/javascript”>
                    dojo.require(“dojo.widget.*”);
                 </script>
                 <script>

                    var dlg;
  &n
bsp;                 function getResults(evt)
                    {
                         var name = dojo.byId(“inputname”).value;
                         dojo.byId(“namediv”).innerHTML = “<b>”+name+”</b>”;
                    }

                    function init(e)
                    {
                        dlg = dojo.widget.byId(“DialogContent”);
                        dojo.event.connect(“hider”, “onclick”, “getResults”);
                    }
                    dojo.addOnLoad(init);
                </script>
        </head>
        <body>
            <a href=“javascript:dlg.show()”>Show Dialog</a>          <br><br>Name:<div id=”namediv”>None</div>

            <div dojoType=“dialog” id=“DialogContent” bgColor=“white” bgOpacity=“0.5″ toggle=“fade” toggleDuration=“250″ closeNode=“hider”>
            <h3>First Dialog</h3>
            <form onsubmit=“return false;”>
                <table>
                    <tr>
                        <td>Name:</td>
                        <td><input type=“text” id=”inputname”></td>
                    </tr>
                    <tr>
                        <td>Description:</td>
                        <td><input type=“text”></td>
                    </tr>
                    <tr>
                        <td>Location:</td>
                        <td><input type=“file”></td>
                    </tr>
                    <tr>
                        <td colspan=“2″ align=“center”> <input type=“button” id=“hider” value=“OK”></td>
                    </tr>
                </table>
            </form>
        </div>
        </body>
    </html>

    The first thing that happens here is that we load the file dojo.js, where among other things the dojo.require function is defined. Then we call that require function for the things we really need in our page. We could have just added a lot of script statements to get pretty much the same effect, but what’s col with the require loader is that we can use wildcards to load a whole package at a time, for instance dojo.widget.*.  This OK when doing happy testing, but in production it’s a good idea to only load what you need.

    Note also that the package structure of dojo is the same as the file structure, and actually derives from it. This means that if you create subdirectories for your own dojo-derived widgets or whatever, you can use the loader for them as well.

Then comes a script section were we define the variables and setup function to use in the page, which are page-specific. We could have taken these out and put them in a separate file, which we then could load using the standard script tag. As long as it’s only a dozen lines or so, I actually prefer to have them in the html file, if the logic is tightly coupled (as in this case) to the nearby elements.

There are two function, one obvious
callback function, which reads the value of an input field, and copies that the value of another element on the page. The other function is a setup function which calls the first function when the form is closed. It does so using dojos own dojo.event.connect function, which is very powerful and requires an article in its own right, but for our purposes here it suffices to say that it hides any browser quirks, to make events simpler to work with.

The rest of the page consist of two parts; A link which shows the dialog form, and the dialog form itself. Note the lazy javascript in the href of the anchor tag, which uses the variable defined earlier to show the dialog.

The second part of the page shows the standard dojo way of declaring widgets, by adding a ‘dojotype’ tag inside the element, which defines the type of widget to be created for the element. Note also the tag ‘closeNode’, which defines which node controls calls to the hide() function of the dialog.

When the link is clicked on the page, the dialog is shown, and when the “OK” button is clicked the dialog is hidden and the getResults() function is called.

Posted in Articles | Leave a comment