Top Banner

of 25

Ajax Stands Fora Synchronous Javascript and XML

Apr 06, 2018

Download

Documents

bumbole
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    1/25

    AJAX stands for Asynchronous JavaScript And XML.

    What You Should Already Know

    Before you continue you should have a basic understanding of the following:

    HTML / XHTML

    JavaScript

    If you want to study these subjects first, find the tutorials on our Home page.

    AJAX = Asynchronous JavaScript and XML

    AJAX is not a new programming language, but a technique for creating better, faster, and moreinteractive web applications.

    With AJAX, your JavaScript can communicate directly with the server, using the JavaScript

    XMLHttpRequest object. With this object, your JavaScript can trade data with a web server,without reloading the page.

    AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server,allowing web pages to request small bits of information from the server instead of whole pages.

    The AJAX technique makes Internet applications smaller, faster and more user-friendly.

    AJAX is a browser technology independent of web server software.

    AJAX is Based on Web Standards

    AJAX is based on the following web standards:

    JavaScript

    XML

    HTML

    CSS

    The web standards used in AJAX are well defined, and supported by all major browsers. AJAX

    applications are browser and platform independent.

    AJAX is About Better Internet Applications

    Web applications have many benefits over desktop applications; they can reach a larger audience,they are easier to install and support, and easier to develop.

    However, Internet applications are not always as "rich" and user-friendly as traditional desktopapplications.

    http://www.w3schools.com/default.asphttp://www.w3schools.com/default.asp
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    2/25

    With AJAX, Internet applications can be made richer and more user-friendly.

    AJAX Uses HTTP Requests

    In traditional JavaScript coding, if you want to get any information from a database or a file on the

    server, or send user information to a server, you will have to make an HTML form and GET or POSTdata to the server. The user will have to click the "Submit" button to send/get the information, wait

    for the server to respond, then a new page will load with the results.

    Because the server returns a new page each time the user submits input, traditional web

    applications can run slowly and tend to be less user-friendly.

    With AJAX, your JavaScript communicates directly with the server, through the JavaScript

    XMLHttpRequest object

    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 user will stay on the same page, and he or she will not notice thatscripts request pages, or send data to a server in the background.

    The XMLHttpRequest Object

    By using the XMLHttpRequest object, a web developer can update a page with data from

    the server after the page has loaded!

    AJAX was made popular in 2005 by Google (with Google Suggest).

    Google Suggestis using the XMLHttpRequest object to create a very dynamic web interface: Whenyou start typing in Google's search box, a JavaScript sends the letters off to a server and the server

    returns a list of suggestions.

    The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox,Opera 8+, and Netscape 7.

    Your First AJAX Application

    To understand how AJAX works, we will create a small AJAX application.

    First, we are going to create a standard HTML form with two text fields: username and time. Theusername field will be filled in by the user and the time field will be filled in using AJAX.

    The HTML file will be named "testAjax.htm", and it looks like this (notice that the HTML form belowhas no submit button!):

    http://www.google.com/webhp?complete=1http://www.google.com/webhp?complete=1http://www.google.com/webhp?complete=1
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    3/25

    Name: Time:

    The next chapters will explain the keystones of AJAX.

    AJAX - Browser Support

    The keystone of AJAX is the XMLHttpRequest object.

    Different browsers use different methods to create the XMLHttpRequest object.

    Internet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript objectcalled XMLHttpRequest.

    To create this object, and deal with different browsers, we are going to use a "try and catch"statement. You can read more about thetry and catch statementin our JavaScript tutorial.

    Let's update our "testAjax.htm" file with the JavaScript that creates the XMLHttpRequest object:

    function ajaxFunction(){var xmlHttp;try{

    // Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}

    catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

    catch (e){try{

    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}catch (e){alert("Your browser does not support AJAX!");return false;}

    }}

    }

    http://www.w3schools.com/js/js_try_catch.asphttp://www.w3schools.com/js/js_try_catch.asphttp://www.w3schools.com/js/js_try_catch.asphttp://www.w3schools.com/js/js_try_catch.asp
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    4/25

    Name: Time:

    Example explained: First create a variable xmlHttpto hold the XMLHttpRequest object.

    Then try to create the object with XMLHttp=new XMLHttpRequest(). This is for the Firefox, Opera,and Safari browsers. If that fails, try xmlHttp=new ActiveXObject("Msxml2.XMLHTTP") which is for

    Internet Explorer 6.0+, if that also fails, try xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")which is for Internet Explorer 5.5+

    If none of the three methods work, the user has a very outdated browser, and he or she will get analert stating that the browser doesn't support AJAX.

    Note: The browser-specific code above is long and quite complex. However, this is the code youcan use every time you need to create an XMLHttpRequest object, so you can just copy and paste it

    whenever you need it. The code above is compatible with all the popular browsers: InternetExplorer, Opera, Firefox, and Safari.

    The next chapter shows how to use the XMLHttpRequest object to communicate with the server.

    AJAX - More About the XMLHttpRequest Object

    Before sending data to the server, we have to explain three important properties of theXMLHttpRequest object.

    The onreadystatechange Property

    After a request to the server, we need a function that can receive the data that is returned by theserver.

    The onreadystatechange property stores the function that will process the response from a server.The following code defines an empty function and sets the onreadystatechange property at the

    same time:

    xmlHttp.onreadystatechange=function(){// We are going to write some code here}

    The readyState Property

    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

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    5/25

    2 The request has been sent

    3 The request is in process

    4 The request is complete

    We are going to add an If statement to the onreadystatechange function to test if our response iscomplete (this means that we can get our data):

    xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4){// Get the data from the server's response}

    }

    The responseText Property

    The data sent back from the server can be retrieved with the responseText property.

    In our code, we will set the value of our "time" input field equal to responseText:

    xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4){document.myForm.time.value=xmlHttp.responseText;}

    }

    AJAX - Sending a Request to the Server

    To send off a request to the server, we use the open() method and the send() method.

    The open() method takes three arguments. The first argument defines which method to use whensending the request (GET or POST). The second argument specifies the URL of the server-side

    script. The third argument specifies that the request should be handled asynchronously. The send()method sends the request off to the server. If we assume that the HTML and ASP file are in thesame directory, the code would be:

    xmlHttp.open("GET","time.asp",true);xmlHttp.send(null);

    Now we must decide when the AJAX function should be executed. We will let the function run"behind the scenes" when the user types something in the username text field:

    Name: Time:

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    6/25

    Our updated AJAX-ready "testAjax.htm" file now looks like this:

    function ajaxFunction(){var xmlHttp;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}

    catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

    catch (e)

    {try{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

    catch (e){alert("Your browser does not support AJAX!");return false;}

    }}xmlHttp.onreadystatechange=function(){

    if(xmlHttp.readyState==4){document.myForm.time.value=xmlHttp.responseText;}

    }xmlHttp.open("GET","time.asp",true);xmlHttp.send(null);

    }Name: Time:

    The next chapter makes our AJAX application complete with the "time.asp" script.

    AJAX - The Server-Side ASP Script

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    7/25

    Now we are going to create the script that displays the current server time.

    The responseText property (explained in the previous chapter) will store the data returned from theserver. Here we want to send back the current time. The code in "time.asp" looks like this:

    Note: The Expires property sets how long (in minutes) a page will be cached on a browser before itexpires. If a user returns to the same page before it expires, the cached version is displayed.Response.Expires=-1 indicates that the page will never be cached.

    Run Your AJAX Application

    Try the AJAX application by typing some text into the Name text box below, then click inside theTime text box:

    Name: Time:

    The Time text box gets the server's time from "time.asp" file without reloading the page

    AJAX Suggest Example

    In the AJAX example below we will demonstrate how a web page can communicate with a web

    server online as a user enters data into a standard HTML form.

    Type a Name in the Box Below

    First Name:

    Suggestions:

    Example Explained - The HTML Form

    The form above has the following HTML code:

    First Name:

    Suggestions:

    As you can see it is just a simple HTML form with an input field called "txt1".

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    8/25

    An event attribute for the input field defines a function to be triggered by the onkeyup event.

    The paragraph below the form contains a span called "txtHint". The span is used as a placeholderfor data retrieved from the web server.

    When the user inputs data, a function called "showHint()" is executed. The execution of the function

    is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away froma keyboard key inside the input field, the function showHint is called.

    Example Explained - The showHint() Function

    The showHint() function is a very simple JavaScript function placed in the section of the

    HTML page.

    The function contains the following code:

    function showHint(str){if (str.length==0){document.getElementById("txtHint").innerHTML="";return;}

    xmlHttp=GetXmlHttpObject()if (xmlHttp==null){alert ("Your browser does not support AJAX!");return;}

    var url="gethint.asp";url=url+"?q="+str;url=url+"&sid="+Math.random();xmlHttp.onreadystatechange=stateChanged;

    xmlHttp.open("GET",url,true);xmlHttp.send(null);}

    The function executes every time a character is entered in the input field.

    If there is some input in the text field (str.length > 0) the function executes the following:

    Defines the url (filename) to send to the server

    Adds a parameter (q) to the url with the content of the input field

    Adds a random number to prevent the server from using a cached file

    Creates an XMLHTTP object, and tells the object to execute a function called stateChanged

    when a change is triggered Opens the XMLHTTP object with the given url.

    Sends an HTTP request to the server

    If the input field is empty, the function simply clears the content of the txtHint placeholder.

    Example Explained - The GetXmlHttpObject() Function

    The example above calls a function called GetXmlHttpObject().

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    9/25

    The purpose of the function is to solve the problem of creating different XMLHTTP objects fordifferent browsers.

    The function is listed below:

    function GetXmlHttpObject()

    { var xmlHttp=null;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}

    catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

    catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

    }return xmlHttp;

    }

    Example Explained - The stateChanged() Function

    The stateChanged() function contains the following code:

    function stateChanged()

    {if (xmlHttp.readyState==4){document.getElementById("txtHint").innerHTML=xmlHttp.responseText;}}

    The stateChanged() function executes every time the state of the XMLHTTP object changes.

    When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with theresponse text.

    AJAX Source Code to Suggest Example

    The source code below belongs to the AJAX example on the previous page.

    You can copy and paste it, and try it yourself.

    The AJAX HTML Page

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    10/25

    This is the HTML page. It contains a simple HTML form and a link to a JavaScript.

    First Name:

    Suggestions:

    The JavaScript code is listed below.

    The AJAX JavaScript

    This is the JavaScript code, stored in the file "clienthint.js":

    var xmlHttp

    function showHint(str){if (str.length==0){document.getElementById("txtHint").innerHTML="";return;}

    xmlHttp=GetXmlHttpObject()

    if (xmlHttp==null){alert ("Your browser does not support AJAX!");return;}

    var url="gethint.asp";url=url+"?q="+str;url=url+"&sid="+Math.random();xmlHttp.onreadystatechange=stateChanged;xmlHttp.open("GET",url,true);xmlHttp.send(null);}

    function stateChanged(){if (xmlHttp.readyState==4){document.getElementById("txtHint").innerHTML=xmlHttp.responseText;}}

    function GetXmlHttpObject(){var xmlHttp=null;try

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    11/25

    {// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}

    catch (e){// Internet Explorer

    try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

    catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

    }return xmlHttp;}

    The AJAX Server Page - ASP and PHP

    There is no such thing as an AJAX server. AJAX pages can be served by any internetserver.

    The server page called by the JavaScript in the example from the previous chapter is a simple ASPfile called "gethint.asp".

    Below we have listed two examples of the server page code, one written in ASP and one in PHP.

    AJAX ASP Example

    The code in the "gethint.asp" page is written in VBScript for an Internet Information Server (IIS). It

    just checks an array of names and returns the corresponding names to the client:

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    12/25

    a(18)="Cindy"a(19)="Doris"a(20)="Eve"a(21)="Evita"a(22)="Sunniva"a(23)="Tove"a(24)="Unni"

    a(25)="Violet"a(26)="Liza"a(27)="Elizabeth"a(28)="Ellen"a(29)="Wenche"a(30)="Vicky"'get the q parameter from URLq=ucase(request.querystring("q"))'lookup all hints from array if length of q>0if len(q)>0 thenhint=""for i=1 to 30if q=ucase(mid(a(i),1,len(q))) thenif hint="" then

    hint=a(i)elsehint=hint & " , " & a(i)

    end ifend if

    nextend if'Output "no suggestion" if no hint were found'or output the correct valuesif hint="" thenresponse.write("no suggestion")

    elseresponse.write(hint)

    end if

    %>

    AJAX PHP Example

    The code above rewritten in PHP.

    Note: To run the entire example in PHP, remember to change the value of the url variable in

    "clienthint.js" from "gethint.asp" to "gethint.php".

    PHP Example

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    13/25

    $a[]="Gunda";$a[]="Hege";$a[]="Inga";$a[]="Johanna";$a[]="Kitty";$a[]="Linda";$a[]="Nina";

    $a[]="Ophelia";$a[]="Petunia";$a[]="Amanda";$a[]="Raquel";$a[]="Cindy";$a[]="Doris";$a[]="Eve";$a[]="Evita";$a[]="Sunniva";$a[]="Tove";$a[]="Unni";$a[]="Violet";$a[]="Liza";$a[]="Elizabeth";

    $a[]="Ellen";$a[]="Wenche";$a[]="Vicky";//get the q parameter from URL$q=$_GET["q"];//lookup all hints from array if length of q>0if (strlen($q) > 0){$hint="";for($i=0; $i

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    14/25

    ?>

    AJAX can be used for interactive communication with a database.

    AJAX Database Example

    In the AJAX example below we will demonstrate how a web page can fetch information from a

    database using AJAX technology.

    Select a Name in the Box Below

    Select a Customer:Customer info will be listed here.

    AJAX Example Explained

    The example above contains a simple HTML form and a link to a JavaScript:

    Select a Customer:Alfreds FutterkisteNorth/SouthWolski Zajazd

    Customer info will be listed here.

    As you can see it is just a simple HTML form with a drop down box called "customers".

    The paragraph below the form contains a div called "txtHint". The div is used as a placeholder forinfo retrieved from the web server.

    When the user selects data, a function called "showCustomer()" is executed. The execution of thefunction is triggered by the "onchange" event. In other words: Each time the user change the value

    in the drop down box, the function showCustomer is called.

    The JavaScript code is listed below.

    The AJAX JavaScript

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    15/25

    This is the JavaScript code stored in the file "selectcustomer.js":

    var xmlHttp

    function showCustomer(str){xmlHttp=GetXmlHttpObject();if (xmlHttp==null){alert ("Your browser does not support AJAX!");return;}

    var url="getcustomer.asp";url=url+"?q="+str;url=url+"&sid="+Math.random();xmlHttp.onreadystatechange=stateChanged;xmlHttp.open("GET",url,true);xmlHttp.send(null);}

    function stateChanged()

    {if (xmlHttp.readyState==4){document.getElementById("txtHint").innerHTML=xmlHttp.responseText;}}

    function GetXmlHttpObject(){var xmlHttp=null;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();

    }catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

    catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

    }return xmlHttp;

    }

    The AJAX Server Page

    The server page called by the JavaScript, is a simple ASP file called "getcustomer.asp".

    The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewrittenin PHP, or some other server language.Look at a corresponding example in PHP.

    http://www.w3schools.com/php/php_ajax_database.asphttp://www.w3schools.com/php/php_ajax_database.asphttp://www.w3schools.com/php/php_ajax_database.asphttp://www.w3schools.com/php/php_ajax_database.asp
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    16/25

    The code runs an SQL against a database and returns the result as an HTML table:

    AJAX XML Example

    In the AJAX example below we will demonstrate how a web page can fetch information from an XMLfile using AJAX technology.

    Select a CD in the Box Below

    Select a CD:CD info will be listed here.

    AJAX Example Explained

    The example above contains a simple HTML form and a link to a JavaScript:

    Select a CD:Bob DylanBonnie TylerDolly Parton

    CD info will be listed here.

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    17/25

    As you can see it is just a simple HTML form with a simple drop down box called "cds".

    The paragraph below the form contains a div called "txtHint". The div is used as a placeholder forinfo retrieved from the web server.

    When the user selects data, a function called "showCD" is executed. The execution of the function istriggered by the "onchange" event. In other words: Each time the user change the value in the dropdown box, the function showCD is called.

    The JavaScript code is listed below.

    The AJAX JavaScript

    This is the JavaScript code stored in the file "selectcd.js":

    var xmlHttpfunction showCD(str){xmlHttp=GetXmlHttpObject();if (xmlHttp==null){alert ("Your browser does not support AJAX!");return;}

    var url="getcd.asp";url=url+"?q="+str;url=url+"&sid="+Math.random();xmlHttp.onreadystatechange=stateChanged;

    xmlHttp.open("GET",url,true);xmlHttp.send(null);}function stateChanged(){if (xmlHttp.readyState==4){document.getElementById("txtHint").innerHTML=xmlHttp.responseText;}}function GetXmlHttpObject(){var xmlHttp=null;try

    {// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}

    catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    18/25

    }catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

    }return xmlHttp;

    }

    The AJAX Server Page

    The server page called by the JavaScript, is a simple ASP file called "getcd.asp".

    The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten

    in PHP, or some other server language.Look at a corresponding example in PHP.

    The code runs a query against an XML file and returns the result as HTML:

    While responseText returns the HTTP response as a string, responseXML returns theresponse as XML.

    The ResponseXML property returns an XML document object, which can be examined andparsed using W3C DOM node tree methods and properties.

    AJAX ResponseXML Example

    In the following AJAX example we will demonstrate how a web page can fetch information from a

    database using AJAX technology. The selected data from the database will this time be converted toan XML document, and then we will use the DOM to extract the values to be displayed.

    Select a Name in the Box Below

    http://www.w3schools.com/php/php_ajax_xml.asphttp://www.w3schools.com/php/php_ajax_xml.asphttp://www.w3schools.com/php/php_ajax_xml.asphttp://www.w3schools.com/php/php_ajax_xml.asp
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    19/25

    Select a Customer:

    AJAX Example Explained

    The example above contains an HTML form, several elements to hold the returned data,and a link to a JavaScript:

    Select a Customer:

    Alfreds FutterkisteNorth/SouthWolski Zajazd


    The example above contains an HTML form with a drop down box called "customers".

    When the user selects a customer in the dropdown box, a function called "showCustomer()" is

    executed. The execution of the function is triggered by the "onchange" event. In other words: Eachtime the user change the value in the drop down box, the function showCustomer() is called.

    The JavaScript code is listed below.

    The AJAX JavaScript

    This is the JavaScript code stored in the file "selectcustomer_xml.js":

    var xmlHttpfunction showCustomer(str){xmlHttp=GetXmlHttpObject();if (xmlHttp==null){alert ("Your browser does not support AJAX!");return;}

    var url="getcustomer_xml.asp";

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    20/25

    url=url+"?q="+str;url=url+"&sid="+Math.random();xmlHttp.onreadystatechange=stateChanged;xmlHttp.open("GET",url,true);xmlHttp.send(null);}function stateChanged()

    {if (xmlHttp.readyState==4){var xmlDoc=xmlHttp.responseXML.documentElement;document.getElementById("companyname").innerHTML=xmlDoc.getElementsByTagName("compname")[0].childNodes[0].nodeValue;document.getElementById("contactname").innerHTML=xmlDoc.getElementsByTagName("contname")[0].childNodes[0].nodeValue;document.getElementById("address").innerHTML=xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;document.getElementById("city").innerHTML=xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;document.getElementById("country").innerHTML=xmlDoc.getElementsByTagName("country")[0].childNodes[0].nodeValue;

    }}

    function GetXmlHttpObject(){var xmlHttp=null;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}

    catch (e){// Internet Explorer

    try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

    catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

    }return xmlHttp;}

    The showCustomer() and GetXmlHttpObject() functions above are the same as in previous chapters.The stateChanged() function is also used earlier in this tutorial, however; this time we return the

    result as an XML document (with responseXML) and uses the DOM to extract the values we want tobe displayed.

    The AJAX Server Page

    The server page called by the JavaScript, is a simple ASP file called "getcustomer_xml.asp".

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    21/25

    The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewrittenin PHP, or some other server language.Look at a corresponding example in PHP.

    The code runs an SQL query against a database and returns the result as an XML document:

    Notice the second line in the ASP code above: response.contenttype="text/xml". The ContentTypeproperty sets the HTTP content type for the response object. The default value for this property is"text/html". This time we want the content type to be XML.

    Then we select data from the database, and builds an XML document with the data.

    AppML is an open source initiative from W3Schools.

    AppML uses AJAX technology.

    What is AppML?

    AppML stands for Application Markup Language AppML uses XML to describe Internet applications

    AppML applications are self-describing

    AppML is a declarative language

    AppML is platform independent

    AppML uses AJAX technology

    AppML is an open source initiative from W3Schools

    http://www.w3schools.com/php/php_ajax_responsexml.asphttp://www.w3schools.com/php/php_ajax_responsexml.asphttp://www.w3schools.com/php/php_ajax_responsexml.asphttp://www.w3schools.com/php/php_ajax_responsexml.asp
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    22/25

    AppML is a Declarative Language

    AppML is not a programming language. It is a declarative language, used to describe

    applications.

    With AppML you can create Internet applications without programming.

    Traditional applications are written in a programming language and compiled, with predefined datastructures and functions. AppML allows the programmer to redefine both data and functions while

    the application is running.

    Since AppML applications are written in XML, AppML applications are self-describing.

    AppML is Browser Independent

    Since AppML only uses internet standards like HTML (XHTML), CSS, XML, and JavaScript, AppML will

    run in all browsers.

    AppML Uses AJAX Technology

    AppML uses AJAX technology. Internet communication between the web client and the web server isdone with HTTP requests.

    Ajax in Struts: implementing dependent select boxes

    In this posting, I want to explain how I have made use of AJAX in a Struts application

    On my current project, Im building a Struts-based web application with many input forms.Many of these forms contain two or more dependable html select boxes. This means, whenyou have two dependable boxes, that the available options in the second selectbox dependson the value selected in the first selectbox. To do this there are three possible solutions:

    Use javascript arrays, where each set of options l inks to an option in the first select-box

    Use an onchange on the first select box to automatically submit the form to go back to the

    server, collect the new options for the second box and regenerate the whole page

    Use Ajax to asynchronously retrieve the new options for the second box

    The first option is not what we wanted: it means that we have to implement a lot of logic inthe html-page, which is visible to the outside world and in common javascript isnt the easiest

    language to debug . The second option is better, but has the big disadvantage that youhave to do a complete round trip to the server to collect the new options and after that the

    http://www.it-eye.nl/weblog/2005/12/13/ajax-in-struts-implementing-dependend-select-boxes/http://www.it-eye.nl/weblog/2005/12/13/ajax-in-struts-implementing-dependend-select-boxes/
  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    23/25

    whole page is regenerated again where actually only the second box is updated..a lot ofoverhead..

    So we decided to use AJAX to solve our problem of dependend select-boxes.

    Because Struts does not have AJAX support yet (wait for Shale..) we have to add it ourselves.

    Because AJAX is not a framework but just a technique to make webpages more dynamic usingJavascript and DHTML, it is quite easy to use it in combination with struts.

    First we make a small html form:

    ...

    -First choose above-

    Now we have to implement our javascript part:

    var req;/*

    * Get the second options by calling a Struts action*/

    function retrieveSecondOptions(){

    firstBox = document.getElementById('firstBox');

    //Nothing selected if(firstBox.selectedIndex==0){ return; } selectedOption = firstBox.options[firstBox.selectedIndex].value; //get the (form based) params to push up as part of the get request url="retrieveSecondOptionsAjaxAction.do?selectedOption= "+selectedOption;

    //Do the Ajax call if(window.XMLHttpRequest){ // Non-IE browsers req = new XMLHttpRequest(); //A call-back function is define so the browser knows which function to call after the server gives areponse back req.onreadystatechange = populateSecondBox; try { req.open("GET", url, true); //was get } catch (e) { alert("Cannot connect to server);

    }req.send(null);

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    24/25

    } else if (window.ActiveXObject) { // IEreq = new ActiveXObject("Microsoft.XMLHTTP");if (req) {

    req.onreadystatechange = populateSecondBox;req.open("GET", url, true);req.send();

    }}

    }

    //Callback functionfunction populateSecondBox(){

    document.getElementById('secondBox').options.length = 0;

    if (req.readyState == 4) { // Completeif (req.status == 200) { // OK response

    textToSplit = req.responseTextif(textToSplit == '803'){

    alert("No select option available on the server")}

    //Split the documentreturnElements=textToSplit.split("||")

    //Process each of the elementsfor ( var i=0; i

  • 8/3/2019 Ajax Stands Fora Synchronous Javascript and XML

    25/25

    public class RetrieveSecondOptionsAjaxAction extends Action { /**

    * This is the main action called from the Struts framework.* @param mapping The ActionMapping used to select this instance.

    * @param form The optional ActionForm bean for this request.* @param request The HTTP Request we are processing.* @param response The HTTP Response we are processing.* @throwsjavax.servlet.ServletException* @throwsjava.io.IOException* @return

    */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Logger logger = Logger.getLogger(getClass()); logger.info( "========================================================== "); logger.info("Starting in RetrieveSecondOptionsAjaxAction");

    String optionSelected = request.getParameter("optionSelected");

    //Check of het soortId wel correct is if(ValidationSupport.isEmptyString(selectedOption))

    { logger.debug("No selected option supplied");

    PrintWriter out = response.getWriter(); out.print("803"); } else { List options = getSecondOptions(selectedOption); //Make a String representation where each option is seperated by '||' and a valua and a label by ';' String outLine = makeOutputString(options); out.print(outLine);

    }}

    return null; }

    As you can see it is quite simple to use AJAX in a Struts application. The great benefit above anormal round trip to the server to dynamically update a webpage is that by using AJAX youonly updated those parts of a page that have to be updated. Because AJAX performs anasynchronous call to the server the user is able to work further.