Valdosta State University



AJAX IntroductionThis is a high-level introduction to AJAX.What is AJAX?33623254191000AJAX is a technique that allows a page to communicate with the server asynchronously. It is used in most web applications. An example is Google’s suggestion list that appears as you type in the search box. As you type, in the background AJAX is used to send the character(s) you are typing to the server. The server searches for topics that match and sends the results back to the browser which renders it. All the while, the user can keep typing. AJAX is an acronym for Asynchronous JavaScript and XML. It is not a programming language, but rather a technique that uses existing technologies (JavaScript and XML).Up to now we have used a synchronous model where web forms post-back to the server. The user interacts with a web form, submits it, and then waits until the server responds. The user cannot interact with the page while it awaits a response. When server responds the whole page is redrawn.AJAX allows the client to post-back to the server asynchronously allowing the user to continue to interact with the page, while in the background a JavaScript event handler awaits the response from the server. When the response occurs, the JavaScript event handler receives data from the server and updates a portion of the page.An easy way to tell if AJAX is being used is to watch the tab in the browser. If you interact with the page, say click a button, and the tab does not flicker, then AJAX is being used. If the tab flickers then AJAX is not being used, e.g a post-back is occurring. When to use AJAX?The link below lists some problems that occurred in a moderately sized application. The responders say that these are taken care of easily with the proper techniques, best practices: This is a very brief article where you click through 30 or so slides each with a sentence or two. It is an excellent presentation about when to use AJAX, why, and when not to use it. You should be able to answer these questions: When to use GET and POST with AJAX sites are coded to work with or without AJAX because a browser may not support JavaScript, which is fairly rare, but must be accommodated in some situations. Answers here do say that AJAX is not ADA compliant. with JavaScriptThese notes explain how AJAX is coded from the ground up, not using any libraries other than the XMLHttpRequest object. It is followed by several examplesHow does AJAX Work?The general idea:More Detail:Example 1We start with a simple example where the user types in a name and we use AJAX to display suggestions:The HTML:Enter a name: // show_suggestion called as user types<input id="txtName" onkeyup="show_suggestion(this.value);" type="text" name="txtName" />// The suggestion list<div class="style1" id="nameList"></div>The client-side code called when the user types in the text box:var xmlHttp; function show_suggestion(strName) {// Clear the suggestions list if user hasn’t entered anythingif (strName.length == 0) {document.getElementById("nameList").innerHTML = ''; return; } // Create XMLHttpRequest object.xmlHttp = new XMLHttpRequest();// Set call-back function (called when the response is received from the server.) xmlHttp.onreadystatechange = displayNames;// Set and send the request.xmlHttp.open("GET", "suggestions.aspx?q=" + strName", true);xmlHttp.send();} The client-side code called when the server responds:function displayNames() {// readyState of 4 or 'complete' represents that data has been returned.if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {// Erase the suggestions if the response doesn’t contain anything.if (xmlHttp.responseText.length==0) {document.getElementById("nameList").innerHTML="***No suggestions"; return; }// Set the response into the name list.document.getElementById("nameList").innerHTML = xmlHttp.responseText;} } The server-side code found in suggestions.aspx.cs:protected void Page_Load(object sender, EventArgs e) {GetSuggestions();}private void GetSuggestions() {// Get the request query string strQuery = Request.QueryString["q"].ToString();//Create the string to be sent back in the response. string strSuggestions = "";// An arbitrary array of names that are used as suggestions. string[] arrStrNames = new string[] { "Abbie Hoffman", "Bob Weir", "Bob Dylan", "Bill Monroe", "BB King", "Cat Stevens", "Carly Simon", "Del McCoury", "David Grisman", "Doc Watson", "Earl Scruggs", "Frank Zappa", "Guy Clark", "Greg Allman", "Ian Anderson", "Jack Williams", "John Doe", "Jimi Hendrix","Janis Joplin", "Jerry Garcia", "Jimmy Rogers", "Peter Rowan", "Pete Townsend", "Townes Van Zandt", "Verlon Thompson" };// Loop through the names, appending matches for (int i = 0; i < arrStrNames.GetLength(0); i++){// Make sure input is smaller than the current name from the list.if (strQuery.Length <= arrStrNames[i].Length)// See if the current name begins with the input string. if (arrStrNames[i].ToLower().Substring(0, strQuery.Length).Equals(strQuery.ToLower())){// Add name and title as an xml element.strSuggestions += arrStrNames[i] + ", ";}}// Send the responseResponse.Write(strSuggestions);// End the page lifecycle and flush buffer.Response.End();} Example 2This example is similar except that the suggestions are hyperlinks which when clicked fills the text box. This is a hard-coded example on the client-side and uses XML and XSLT on the server side.The code works like this:The server-side code goes through a loop finding matches and building an XML string to store the results.// Add name and title as an xml element.strXmlNames += "<artist><name>" + arrStrNames[i, 0] + "</name>";strXmlNames += "<title>" + arrStrNames[i, 1] + "</title></artist>";The XML is transformed with this XSLT below. Notice that a hyperlink is built which calls a JavaScript function.<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl=""> <xsl:template match="/"> <xsl:for-each select="artists/artist"> <a style="Font-Size: Smaller" href="javascript:" onclick="useName(this.innerHTML)"><xsl:value-of select="name" /></a><span style="Font-Size: Smaller" > - <xsl:value-of select="title" /></span><br /> </xsl:for-each> </xsl:template> </xsl:stylesheet>The useName JavaScript functionfunction useName(anchor) {if( typeof(anchor) == "undefined" )document.getElementById("txtName").value = "";elsedocument.getElementById(("txtName").value = anchor; document.getElementById("nameList").innerHTML = ''; document.getElementById("suggestions").style.visibility = 'hidden';}AJAX with jQueryThese notes explain how AJAX is using jQuery.How does AJAX Work?The jQuery Ajax API: , ? Ajax methods: 1This is the same Example 1 from AJAX with JavaScript.We start with a simple example where the user types in a name and we use AJAX to display suggestions:The HTML is shown below. Notice that we do not have the onkeyup event for the text box. We will define that in the Ajax.Enter a name: // show_suggestion called as user types<input id="txtName" type="text" name="txtName" />// The suggestion list<div class="style1" id="nameList"></div>The client-side Ajax code is shown below. Notice that we call the GetSuggestions method directly.function noSuggestions() {$("#nameList").text("***No suggestions");}$(document).ready(function() {$("#txtName").keyup(function () {var userData = $("#txtName").val();if (userData.length == 0)return noSuggestions();$.ajax({type: "GET",url: "Suggestions.aspx/GetSuggestions",data: { q:userData },success: function (response) {if (response.length == 0)return noSuggestions();$("#nameList").text(response);}});});});The server-side code found in suggestions.aspx.cs:private void GetSuggestions() {// Get the request query string strQuery = Request.QueryString["q"].ToString();//Create the string to be sent back in the response. string strSuggestions = "";// An arbitrary array of names that are used as suggestions. string[] arrStrNames = new string[] { "Abbie Hoffman", "Bob Weir", "Bob Dylan", "Bill Monroe", "BB King", "Cat Stevens", "Carly Simon", "Del McCoury", "David Grisman", "Doc Watson", "Earl Scruggs", "Frank Zappa", "Guy Clark", "Greg Allman", "Ian Anderson", "Jack Williams", "John Doe", "Jimi Hendrix","Janis Joplin", "Jerry Garcia", "Jimmy Rogers", "Peter Rowan", "Pete Townsend", "Townes Van Zandt", "Verlon Thompson" };// Loop through the names, appending matches for (int i = 0; i < arrStrNames.GetLength(0); i++) {// Make sure input is smaller than the current name from the list.if (strQuery.Length <= arrStrNames[i].Length)// See if the current name begins with the input string. if (arrStrNames[i].ToLower().Substring(0, strQuery.Length).Equals(strQuery.ToLower())) {// Add name and title as an xml element.strSuggestions += arrStrNames[i] + ", ";}}// Send the responseResponse.Write(strSuggestions);// End the page lifecycle and flush buffer.Response.End();} AJAX in .NETThis explains how to use the built-in features for AJAX in .NET.How to use Ajax with .NETAdd a ScriptManager to the page (Toolbox, Ajax Extentions). A line like this will be added to the top of the Source, just inside the body tag.<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>Add an UpdatePanel where you want partial-page updates and add relevant controls.<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate><%--Put controls here.--%> </ContentTemplate></asp:UpdatePanel>If needed, add Trigger(s) to UpdatePanel for controls outside UpdatePanel that trigger the Ajax call<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate><%--Put controls here.--%> </ContentTemplate><Triggers><asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" /></Triggers></asp:UpdatePanel>...<asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click" Text="Add" />If needed, add an UpdateProgress controlThe Timer ControlThe Timer control is used to call a method on the server on a periodic basis. It fires a Tick event every number of seconds specified in the Interval property.TutorialsOne page description of using AJAX in .NET: two pages of a 5-page tutorial from MS: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download