How to write the AJAX-application

It two years ago AJAX was in wonder (and word AJAX then yet have not invented). Now webs - applications which pages were updated hurriedly, in the nature of things. Even on the contrary: without AJAX it is difficult to imagine some services.


How usual webs - applications worked? As a rule, (cliques under the link or pressing the button) the browser reacted to event by sending of search to the server. When from the server there came the answer, all contents of page were completely updated.


One of problems was, that at updating contents of page the web - application passes in a new status. From the information on the previous status the data transferred{handed} in search are saved only. The more exact information on a former status of system is required, the more than the data it is necessary to send in search.


Other lack is necessity to send repeating data files to the client after each event. For example, if the user was mistaken at filling the form instead of the short message on a mistake it is necessary to load again both the form, and all entered before the information.


The modern browsers supporting standards W3C DOM, allow to deduce{remove} the web - application on a new level.


The circuit of interaction remains almost same. Only sends search and receives the answer from the server now a script on the party  of the client, and instead of updating all page - its{her} part (instead of updating other actions can be undertaken, for example, to be sent the following search) is updated only.


The web - application turns out distributed{allocated}, and the part of logic is on the party  of the client, and a part - on the party  of the server. Such applications also name the term " AJAX Applications " (the abbreviation is deciphered as Asynchronous Javascript And Xml Applications).



Object XMLHTTPRequest


For asynchronous searches from the client to the server on the party  of a browser the special object under name XMLHTTPRequest serves.


We list methods and properties of object which will be used further:


* LHTTPRequest.open ("method", "URL", async, "uname", "pswd") - creates search to the server.

* method - type of search, for example, GET

* URL - URL search, for example httr: // localhost/file.xml

* async - if True the asynchronous search will be used, that is performance of a script will proceed after sending search. Otherwise the script will expect the answer from the server, having frozen UI.

* uname, pswd - a login and the password for simple web - authorization.

* XMLHTTPRequest.send ("content") - sends search about the server. Value content can be the data for POST-search or an empty line.

* XMLHTTPRequest.onreadystatechange - obrabotchik events working on each change of a status of object. Statuses of object can be the following:

* 0 - before the search is sent (uninitialized)

* 1 - the object is initialized (loading)

* 2 - the answer from (loaded server is received

* 3 - connection with the server actively (interactive)

* 4 - the object has finished job (complete)

* XMLHTTPRequest.responseText - returns the data received from the server as a line.

* XMLHTTPRequest.responseXML - if the answer of the server has come as correct XML, returns XML DOM object.

* XMLHTTPRequest.status - returns the status of the HTTP-answer as number. For example, 404 if the required page has not been found on the server.


Let's consider application of object by the example of the simple AJAX-application.



Field SELECT with search


Let's assume at us there is a table, in which about one million recordings. It is necessary for user to choose only one recording from the table (realization of the attitude{relation} " one to many "). The choice of the user is only one of stages of filling of the big web - form.


It is natural, that the user could choose the necessary recording from one million, any search engines of this recording are necessary. For example, simple text search under the name.


In the traditional web - application for this purpose it should to use separate page and to save other given forms in session of the user, or to break process of filling of the form into some stages. In the AJAX-application the additional page is not necessary.


The choice of recording will be realized with the help of two elements of the web - form. The first element is a text field where the user enters a keyword. It is sent on the server, and that returns only those lines from the table which satisfy to a condition of search. The answer of the server (as the list) is located in field SELECT in which the user and will make a final choice. Thus, at sending the form on the server the value chosen in field SELECT as ID recordings from the big table will get.


In HTML looks it can so:



<input type = "text"

   onkeyup = " lookup (this.value, ' id_select ',

   ' http://localhost/cgi-bin/xmlhttp.cgi ') "/>

<select id = "id_select" name = "id_select">

<option selected = "selected" value = ""> </option>

</select>


On any event KeyUp (otzhatie buttons) in a text field function lookup (' the text ',' id-selecta ',' url ') is caused



function lookup (text, select_id, url) {

        // We receive object XMLHTTPRequest

        if (! this.http) {

            this.http = get_http ();

            this.working = false;

}

        // Search

        if (! this.working ** this.http) {

            var http = this.http;

            // If in a text field less than three

            // Symbols - it is not done{is made} anything

            if (text.length <3) return;

// We add the coded text

                // In URL search

            url = url + "? text = " + encodeURIComponent (text);

      // We create search

            this.http.open ("GET", url, true);

            // We attach to search function - obrabotchik

            // Events

            this.http.onreadystatechange = function () {

// 4 - the data are ready for processing

                if (http.readyState == 4) {

                    fill (select_id, http.responseText);

                    this.working = false;

} else {

                     // The data during reception,

                     // It is possible poveselit` the user

                     // Messages

                     // LOOK FORWARD TO HEARING

}

}

            this.working = true;

            this.http.send (null);

}

        if (! this.http) {

              alert (' the Mistake at creation XMLHTTP of object! ')

}

}


Apparently, in the beginning we receive XMLHTTP-object with the help of function get_http (). Then the search text is coded in style URL and the GET-search to the server is formed. URL search in this case will approximately look so: httr: // localhost/cgi-bin/xmlhttp.cgi? text =...


The script on the server, having received value text, does{makes} search in the table and sends result to the client. In obrabotchike events of object XMLHTTP when the data from the server are received and ready to use, function fill (' select_id ',' data ') which will fill in list SELECT the received data is caused.


Function get_http () is a cross-country - brauzernaja realization of reception of object XMLHTTP (in each browser he turns out in own way). Its{her} realization with comments you can easily find on the Internet, it, so to say, an example from the tutorial.



function get_http () {

    var xmlhttp;

    / * cc_on

    @if (_jscript_version> = 5)

        try {

            xmlhttp = new ActiveXObject (" Msxml2. XMLHTTP ");

} catch (e) {

            try {

                xmlhttp = new

                ActiveXObject (" Microsoft. XMLHTTP ");

} catch (E) {

                xmlhttp = false;

}

}

    @else

        xmlhttp = false;

    @end */

    if (! xmlhttp ** typeof XMLHttpRequest! = ' undefined ') {

        try {

            xmlhttp = new XMLHttpRequest ();

} catch (e) {

            xmlhttp = false;

}

}

    return xmlhttp;

}


Function fill () receives on an input{entrance} option value ID of list SELECT which it is necessary to fill, and the data received from the server.


For simplicity we shall assume, that the data from the server we receive as the table which fields are divided{shared} by a symbol of tabulation ' t ', and lines - a symbol of carry of a line ' n ':



id1tname1n

id2tname2n

...


On the basis of contents of this table we shall fill in field SELECT elements OPTION.



function fill (select_id, data) {

    // Field SELECT in a variable as object

    var select = document.getElementById (select_id);

    // We clear SELECT

    select.options.length = 0;

    // If the data no - is not done{made} more than anything

    if (data.length == 0) return;

    // In a file arr - lines of the received table

    var arr = data.split (' n ');

    // For every line

    for (var i in arr) {

        // In a file val - fields of the received table

        val = arr [i] .split (' t ');

        // We add new object OPTION to ours SELECT

        select.options [select.options.length] =

        new Option (val [1], val [0], false, false);

}

}


It is ready. Now for any web - form of the application we can realize a similar choice of value from the mullions-strong list which for the user will look as the read out pressing of keys. In a local area network the choice occurs practically instantly. In case of astable or nizkoskorostnogo connections with the server, it is necessary to notify also the user that loading of the data from the server is not completed yet. It is useful to provide and means for reaction to breakage of connection.