AJAX – Asynchronous java script and XML

Standard

The Methods of XMLHttpRequest object  with java script allow to transport the data between browser and server , similar manner DOM with java also allow to interact with browser content as background process without affecting/render whole page. Later (year 2000) group of these technologies named as AJAX.

Ajax – Asynchronous java script and XML –This mechanism helps to send and render part of the web page instead of postback whole page.  The entire process running in background to get the result without refresh or reload whole page and it gives richest experience to the user.

Google is using this technique to list down the suggested list of search phrases when user interacts with search box.  Gmail, web outlook are other much familiar examples.

Most of the new browsers support XMLHttpRequest, but some of older version supporting XMLHttp ActiveX Object. When we code this background process we have to consider this compatibility.

Syntax:

var xmlHTTPObject 
if (window.XMLHttpRequest)
{
  xmlHTTPObject = new XMLHttpRequest(); 
}
else
{
  xmlHTTPObject = new ActiveXObject(“Microsoft.XMLHttp”);
}

Methods Supported both XMLHttpRequest object and ActivXObjects are

1)      Open(DataSubmissionMethod, url, isAsync)

DataSubmissionMethod either ‘GET’ or ‘POST’. ‘GET’ is recommended and it is faster than ‘POST’.

2)      Send()

Syntax:
…………………………..
xmlHTTPObject.Open(‘GET’, PageToRender.asp, True)
or 
xmlHTTPObject.Open(‘POST’, PageToPost.asp, True)
xmlHTTPObject.Send();
 …………………………

We can monitor the server response using ready state. Either the page submitted or requisition send to the server onreadystatechange event will be fired, using this event we can get the readystate and result of response status values.

a)      Possible values of readystate. No default value assigned.

0 – unintialized – object not initialized
1 – loading – data is loading
2 – loaded – data fully loaded
3 – interactive – request not completed, but user can interact with object
4 – completed – request completed.

b)      Possible values of response status

100 – Continue
101 – Switching protocols
200 – OK
201 – Created
202 – Accepted
203 – Non-Authoritative Information
204 – No Content
205 – Reset Content
206 – Partial Content
300 – Multiple Choices
301 – Moved Permanently
302 – Found
303 – See Other
304 – Not Modified
305 – Use Proxy
307 – Temporary Redirect
400 – Bad Request
401 – Unauthorized
402 – Payment Required
403 – Forbidden
404 – Not Found
405 – Method Not Allowed
406 – Not Acceptable
407 – Proxy Authentication Required
408 – Request Timeout
409 – Conflict
410 – Gone
411 – Length Required
412 – Precondition Failed
413 – Request Entity Too Large
414 – Request-URI Too Long
415 – Unsupported Media Type
416 – Requested Range Not Suitable
417 – Expectation Failed
500 – Internal Server Error
501 – Not Implemented
502 – Bad Gateway
503 – Service Unavailable
504 – Gateway Timeout
505 – HTTP Version Not Supported

Syntax:

xmlHTTPObject.onreadystatechange=function()  {
  if (xmlHTTPObject.readyState==4 && xmlHTTPObject.status==200)
    {
    document.getElementById(“txtResponseText”).value
=xmlHTTPObject.responseText;

}
}

xmlHTTPObject.open(“GET”,”ajax_info.txt”,true);

xmlHTTPObject.send();

ASP.NET AJAX or Microsoft AJAX

Microsoft Ajax is combination of DHTML (Dynamic HTML) and client script libraries with cross browser ECMAScript (java Script). It uses as client script to improve rich user experience to the ASP.NET webpages.

a)      ASP.Net Ajax – ScriptManager Control

Control to loading Microsoft Ajax client script and it helps to enable partial rendering with updatepanel and/or timer controls

b)     ASP.Net Ajax – UpdatePanel Control

Control to enable partial page rendering with ScriptManager control.

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %><!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”><script runat=”server”>
Protected Sub Button1_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles btnPartialPostback.Click
lblPostbackStatus.Text = “Partial Render”
End Sub
Protected Sub Button2_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles btnFullPagePostback.Click
lblPostbackStatus.Text = “Full page render”
End Sub
Protected Sub Page_Load(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Me.Load
lblPartialPostback.Text = DateTime.Now.ToString()
lblFullPagePostback.Text = DateTime.Now.ToString
End Sub
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<div>
</div>
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate>
<div>
<asp:Label
ID=”lblPostbackStatus” runat=”server”></asp:Label>
<br />
<asp:Label ID=”lblPartialPostback” runat=”server” Text=”Label”></asp:Label>
&nbsp;
<asp:Button ID=”btnPartialPostback” runat=”server” Text=”Click Me for Partial page Postback”
/>
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID=”lblFullPagePostback” runat=”server” Text=”Label”></asp:Label>
&nbsp;
<asp:Button ID=”btnFullPagePostback” runat=”server”
Text=”Click Me for Full page Postback” />
</form>
</body>
</html>

-> UpdatePanel – Update Mode Property and its value

1)      Always – Update occur whenever postback

2)      Conditional – Update occurs only in associated triggers fire.

->                      UpdatePanel Triggers collection and it types

1)      AsyncPostBackTrigger

AsyncPostBackTrigger will fire and update content inside the updatepanel with conditional update mode, we have to specifiy control ID (control out side the upadte panel)and event name to partially refresh the content of the corresponding updatepanel.

<script runat=”server”>

    Protected Sub Button1_Click(ByVal sender As Object,
ByVal
e As System.EventArgs)
        Label1.Text = DateTime.Now.ToString()
    End Sub

</script>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>   
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        </asp:ScriptManager>           
        <asp:UpdatePanel ID=”UpdatePanel1″
          runat=”server” ChildrenAsTriggers=”False”
           Updatemode=”Conditional” >
            <ContentTemplate>           
             <asp:Label ID=”Label1″
             runat=”server” Text=”Label”></asp:Label>
            </ContentTemplate>
            <Triggers>
            <asp:PostBackTrigger ControlID=”Button1″ />
            </Triggers>           
        </asp:UpdatePanel>
      <asp:UpdatePanel ID=”UpdatePanel2″ runat=”server”>
      <ContentTemplate>
<asp:Button ID=”Button1″ runat=”server”
           Text=”Button” onclick=”Button1_Click” />
      </ContentTemplate>
      </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>
More Details: http://msdn.microsoft.com/en-us/library/system.web.ui.asyncpostbacktrigger.aspx
2)      PostBackTrigger
c)       UpdateProgress Control
Update Progress control is useful to display the status for user intervention when delaying partial render using update panel and script manager.
<script runat=”server”>
Protected Sub Button1_Click(ByVal sender As Object,
ByVal
e As System.EventArgs) Handles  btnPartialPostback.Click
 lblPostbackStatus.Text = “Partial Render”
System.Threading.Thread.Sleep(3000)
End Sub
</script>
             …………………………………………….
             …………………………………………..
<asp:UpdatePanel>
 ………………………………………………
 ………………………………………………
</asp:UpdatePanel>
    <asp:UpdateProgress ID=”UpdateProgress1″ runat=”server”>
    <ProgressTemplate>
    Update Progress control is useful to display the status when delaying partial render.
    </ProgressTemplate>
    </asp:UpdateProgress>
d)      Timer Control
e)       ScriptManagerProxy

ASP.NET AJAX Control Toolkit

Ajax controls toolkit is the set of predefined ajax enabled controls developed by the open source community, able to plug-in with visual studio and help us to design the robust dynamic web pages.

a)      Calendar Control
This ajax control help to select the date and display into corresponding target control.
<ajaxToolkit:CalendarExtender ID=”CalendarExtender1″ runat=”server”
PopupButtonID=”txtInvDate” TargetControlID=”txtInvDate”>
</ajaxToolkit:CalendarExtender>

b)      CollapsiblePanel Control
This ajax control help to collapse and expand the panel to manage the screen as the user intervention.
<asp:Panel ID=”pnlItemEditor” runat=”server”>

</asp:panel>
<ajaxToolkit:CollapsiblePanelExtender ID=”Colapse2″ runat=”server” TargetControlID=”pnlItemEditor”
CollapseControlID=”LinkButton2″ ExpandControlID =”LinkButton2″ CollapsedText=”Show” ExpandedText=”Hide”
ImageControlID=”ImageButton2″ ExpandedImage=”App_Themes/SMS_Theme/Images/expand_blue.jpg”
CollapsedImage=”App_Themes/SMS_Theme/Images/collapse_blue.jpg” >
</ajaxToolkit:CollapsiblePanelExtender>

c)      ColorPicker Control
This ajax control help to pick the color and its code from color palette dialogue screen

d)      DropDown Control
<asp:panel runat=”server” ID=”panel1”>
<asp:datagrid runat=”server” ID=”datagrid1” datasourceID=”sqldataSource1” onItemDataFound=”datagrid1_onItemDataFound” />
</asp:panel>

e)      ConfirmButton Control
This ajax control help to get the conformation from the user before proceed to the actual task.
<asp:Button ID=”btnSavePO” runat=”server” Text=”Save PO”
SkinID=”normalbtn” ValidationGroup=”A” />
<ajaxToolkit:ConfirmButtonExtender ID=”ConfirmButtonExtender2″ runat=”server”
ConfirmText=”Do you want to save this PO?” TargetControlID=”btnSavePO”
ConfirmOnFormSubmit=”True”>
</ajaxToolkit:ConfirmButtonExtender>

f)       FilteredTextBox Control
This ajax control help to allow or disallow the input characters in the target control.
<asp:TextBox ID=”txtOrderQty” runat=”server” AutoPostBack=”True”
SkinID=”numeric80box”></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID=”FilteredTextBoxExtender1″
runat=”server” TargetControlID=”txtOrderQty” ValidChars=”0123456789.”>
</ajaxToolkit:FilteredTextBoxExtender>

g)      MaskedEdit Control
This ajax control help to allow and validate the input characters in masked format.

h)      ModalPopup Control
This ajax control help to display the popup control as model window screen. (That means user should close this screen before access the parent screen.)

<ajaxToolkit:ModalPopupExtender ID=”mpe_msg” runat=”server”
TargetControlID=”hdnVal” BackgroundCssClass=”modalBackground”
PopupControlID=”tblMsgPopup” CancelControlID=”hdnClose”
PopupDragHandleControlID=”pnlMsgDtl” Y=”200″>
</ajaxToolkit:ModalPopupExtender>

i)        NumericUpDown Control
This ajax control help to display, increase and decrease numeric value using minimum and maximum properties.
<ajaxToolkit:NumericUpDownExtender ID=”NumericUpDownExtender1″
runat=”server”   TargetControlID=”txtNoOfPrint”  Width=”100″
TargetButtonDownID=”Button1″
TargetButtonUpID=”Button2″
Maximum=100 Minimum=1 >
</ajaxToolkit:NumericUpDownExtender>

j)        PasswordStrength Control
This ajax control helps to display the user defined messages and notify the user for password strength as the organization policy (password length, uppercase, lower case, symbol and numeric combination.

<ajaxToolkit:PasswordStrength ID=”psPassword” runat=”server” TargetControlID=”txtNewPassword”
DisplayPosition=”RightSide”
StrengthIndicatorType=”Text”
PreferredPasswordLength=”8″
PrefixText=”Strength:”
HelpStatusLabelID=”lblPasswordStrength”
TextStrengthDescriptions=”Very Poor;Weak;Average;Strong;Excellent”
MinimumNumericCharacters=”0″
MinimumSymbolCharacters=”0″
RequiresUpperAndLowerCaseCharacters=”false”
TextStrengthDescriptionStyles=”TextIndicator_TextBox1_Strength1;TextIndicator_TextBox1_Strength2;TextIndicator_TextBox1_Strength3;TextIndicator_TextBox1_Strength4;TextIndicator_TextBox1_Strength5″ />

k)      TextBoxWatermark Control
This ajax control helps to display the descriptive text or statement displayed (but it is not default input data) in the target control before get the user input.
<asp:TextBox ID=”txtPONumber” runat=”server” AutoPostBack=”True”
SkinID=”codebox” style=”margin-bottom: 0px”></asp:TextBox>
<ajaxToolkit:TextBoxWatermarkExtender ID=”PONumberNew” runat=”server”
TargetControlID=”txtPONumber” WatermarkText=”New”>

More details available at http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/

Reference :
http://www.w3schools.com/ajax/default.asp
http://en.wikipedia.org/wiki/Ajax_(programming)
http://msdn.microsoft.com/en-us/library/ee341002.aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s