Transcript Slide 1

AJAX
1
Topics Covered
 What is AJAX?
 XMLHttpRequest Object
 How Ajax works
 Understanding Ajax with e.g.
 Ajax Server Controls
 Advantages and Disadvantages of AJAX
2
© Copyright 2007 InterGlobe Technologies
What is AJAX?
AJAX (Asynchronous JavaScript and XML)
An Approach to building dynamic web applications uses JavaScript to
make asynchronous calls to the server that typically return XML
- Allows user to continue interacting with web page while waiting for data to
be returned
- Page can be updated without refreshing browser results in a better user
experience
- The communication between the client and server happens asynchronously,
so the client isn’t interrupted
3
© Copyright 2007 InterGlobe Technologies
What is AJAX? Cont…
4
© Copyright 2007 InterGlobe Technologies
XMLHttpRequest Object
 XMLHttpRequest is the Cornerstone of Ajax
 Allows to send requests to the server asynchronously and retrieve the results
Creation of XMLHttpRequest Object
var xmlRequest;
try
{
// This works if XMLHttpRequest is part of JavaScript.
xmlRequest = new XMLHttpRequest();
}
catch(err)
{
// Otherwise, the ActiveX object is required.
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
5
© Copyright 2007 InterGlobe Technologies
XMLHttpRequest Object cont…
 Sending a Request
Two key methods open() and send().
open(): defines the request you want to send to the server.
xmlRequest.open("GET", MyURL);
send(): fires off the request.
xmlRequest.send(null);
 Handling the Response
Property onreadystatechange: attach an event handler
xmlRequest.onreadystatechange = UpdatePage
6
© Copyright 2007 InterGlobe Technologies
How Ajax works
7
© Copyright 2007 InterGlobe Technologies
Understanding AJAX
An AJAX e.g.
8
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
- The Ajax-enabled web page, which includes the client-side code for making
the request through the XMLHttpRequest object
- Another page or resource that can handle the requests from the first page
and send the appropriate response
9
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
Here’s the basic outline of the page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Page</title>
<script type="text/javascript">
<!-- JavaScript functions go here. -->
</script>
</head>
<body onload="CreateXMLHttpRequest();">
<form id="form1" runat="server">
<div>
Value 1:&nbsp;
<asp:TextBox id="txt1" runat="server“ onKeyUp="CallServerForUpdate();" /><br />
10
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
Value 2:&nbsp;
<asp:TextBox id="txt2" runat="server“ onKeyUp="CallServerForUpdate();" /><br /><br />
<asp:Label id="lblResponse" runat="server" ... />
</div>
</form>
</body>
</html>
Creation of CreateXMLHttpRequest, called at onload event
var XmlRequest;
function CreateXMLHttpRequest()
{
// This works if XMLHttpRequest is part of JavaScript.
xmlRequest = new XMLHttpRequest();
}
11
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
CallServerForUpdate() () function called at onKeyUp event of textboxes
function CallServerForUpdate()
{
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var url = "CalculatorCallbackHandler.ashx?value1=" +
txt1.value + "&value2=" + txt2.value;
xmlRequest.open("GET", url);
xmlRequest.onreadystatechange = ApplyUpdate;
xmlRequest.send();
}
12
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
URL
CalculatorCallbackHandler.ashx?value1=" +txt1.value + "&value2=" txt2.value
code for the HTTP handler:
public class CalculatorCallbackHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
HttpResponse response = context.Response;
// Write ordinary text.
response.ContentType = "text/plain";
13
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
// Get the query string arguments.
float value1, value2;
if (Single.TryParse(context.Request.QueryString["value1"], out value1) &&
Single.TryParse(context.Request.QueryString["value2"], out value2))
{
// Calculate the total.
response.Write(value1 + value2);
response.Write(",");
DateTime now = DateTime.Now;
response.Write(now.ToLongTimeString());
}
else
{
// The values weren't supplied or they weren't numbers.
// Indicate an error.
response.Write("-");
}}
14
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
ApplyUpdate() function runs when the response is received
function ApplyUpdate()
{
// Check that the response was received successfully.
if (xmlRequest.readyState == 4)
{
if (xmlRequest.status == 200)
{
var lbl = document.getElementById("lblResponse");
var response = xmlRequest.responseText;
if (response == "-")
{
lbl.innerHTML = "You've entered invalid numbers.";
}
15
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
else
{
var responseStrings = response.split(",");
lbl.innerHTML = "The server returned the sum: " +
responseStrings[0] + " at " + responseStrings[1];
}
}
}
}
16
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
Ajax with Client Callbacks
17
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
Building the Basic Page:
<asp:SqlDataSource id="sourceRegions" runat="server"
ConnectionString="<%$ ConnectionStrings:AIEPreProd %>"
SelectCommand="SELECT * FROM City" />
<asp:DropDownList id=“ddlCity" Runat="server"></asp:DropDownList>
<asp:DropDownList id=“ddlAirport" Width="300px" Runat="server"></asp:DropDownList>
Implementing the Callback:
public partial class ClientCallback : System.Web.UI.Page, ICallbackEventHandler
{ ... }
ICallbackEventHandler interface defines two methods
RaiseCallbackEvent():
GetCallbackResult():
18
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
private string eventArgument;
public void RaiseCallbackEvent(string eventArgument)
{
this.eventArgument = eventArgument;
}
public string GetCallbackResult()
{
// Create the ADO.NET objects.
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings[“AIEPreProd"].ConnectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Airports WHERE Citycode=@ Citycode ", con);
cmd.Parameters.Add(new SqlParameter("@ Citycode ", SqlDbType.Int, 4));
cmd.Parameters["@ Citycode "].Value = Int32.Parse(eventArgument);
19
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
// Create a StringBuilder that contains the response string.
StringBuilder results = new StringBuilder();
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
// Build the response string.
while (reader.Read())
{
results.Append(reader["Airport_Code"]);
results.Append("|");
results.Append(reader["Airport_Name"]);
results.Append("||");
}
reader.Close();
}
20
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
finally
{
con.Close();
}
return results.ToString();
}
Writing the Client-Side Script
<script type="text/javascript">
function ClientCallback(result, context)
{
// Find the list box.
var ddlAirport = document.getElementById("ddlAirport");
// Clear out any content in the list.
ddlAirport.innerHTML= "";
// Get an array with a list of Airport records.
var rows = result.split("||");
21
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
for (var i = 0; i < rows.length - 1; ++i)
{
// Split each record into two fields.
var fields = rows[i].split("|");
var Airportname= fields[0];
var Airportcode= fields[1];
// Create the list item.
var option = document.createElement("option");
// Store the ID in the value attribute.
option.value = Airportcode;
// Show the description in the text of the list item.
option.innerHTML = Airportname;
// Add the item to the end of the list.
ddlAirport.appendChild(option);
}
}
</script>
22
© Copyright 2007 InterGlobe Technologies
Understanding AJAX cont…
Defining onchange event of ddlCity (Dropdown List) using GetCallbackEventReference ()
protected void Page_Load(object sender, EventArgs e)
{
string callbackRef = Page.ClientScript.GetCallbackEventReference(
this, "document.getElementById('ddlCity').value",
"ClientCallback", "null", true);
ddlCity.Attributes["onchange"] = callbackRef;
}
23
© Copyright 2007 InterGlobe Technologies
AJAX Server Controls
24
© Copyright 2007 InterGlobe Technologies
AJAX Server Controls Cont…
Partial List of ASP.Net Ajax Controls:
−
AutoCompleteExtender
−
TabContainer
−
AlwaysVisibleControlExtender
−
CalendarExtender
−
CascadingDropDown-Extender
−
ConfirmButtonExtender
−
Accordion
25
© Copyright 2007 InterGlobe Technologies
AJAX Server Controls Cont…
The AutoCompleteExtender:
<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtName"
ServicePath="AutoCompleteService.asmx“
ServiceMethod="GetNames"
MinimumPrefixLength="1">
</ajaxToolkit:AutoCompleteExtender>
26
© Copyright 2007 InterGlobe Technologies
Advantages and Disadvantages of AJAX
Advantages:
-- developing fast and dynamic website
-- Greater response
-- Page is updated without refresh
-- Reduces load on server resources
-- Continuous interaction with web page
Disadvantages:
-- Ajax wont work if JavaScript is not activated
-- Back button may be deactivated
-- Since data to display are displaying dynamically, they are not
part of the page. (keywords inside are not used by search
engine)
27
© Copyright 2007 InterGlobe Technologies
Thank you
28
© Copyright 2007 InterGlobe Technologies