AJAX for newbies

Now in a network the Internet is observed very active development (and even use) new technologies. One of such technologies - AJAX.

What is AJAX?


AJAX is an abbreviation which means Asynchronous Javascript and XML. Actually, AJAX is not new technology as both Javascript, and XML exist already enough long time, and AJAX is a synthesis of the designated technologies. AJAX more often associriuetsja with term Web 2.0 also it is presented as the newest Web-application.


At use AJAX there is no necessity to update each time all page as its  concrete part is updated only. It is much more convenient, as it is not necessary to wait for a long time, and is more economic, as not everyone possess bezlimitnym the Internet. The truth in this case, it is necessary for developer to watch{keep up}, that the user keeps abreast of that occurs on page. It can be realized with use of indicators of loading, text messages that there is a data exchange with the server. It is necessary to understand also, what not all browsers support AJAX (old versions of browsers and text browsers). Plus Javascript can be switched - off by the user. Therefore, it is not necessary to abuse use of technology and to resort to alternative methods of performance of the information on a Web-site.


Let's generalize advantages AJAX:

?         An opportunity of creation of the convenient Web-interface

?         Active interaction with the user

?         Partial perezagruzka pages, instead of full

?         Convenience of use


AJAX uses two methods of job with web - page: change of Web-page not reloading her , and the dynamic reference{manipulation} to the server. The second can be carried out in several ways, in particular, XMLHttpRequest about what we and shall speak, and use of technics{technical equipment} of the latent frame.

Data exchange



To carry out data exchange, on page object XMLHttpRequest which is the original intermediary between the Browser of the user and the server (fig. 1) should be created. With help XMLHttpRequest it is possible to send search about the server, and also to receive the answer as a various sort of the data.


To exchange the data with the server it is possible in two ways. The first way is a GET-search. In this search you address to the document on the server, passing him arguments through itself URL. Thus on the party  of the client it will be logical to use function Javascript ` and escape that some data have not interrupted search.


It is not recommended to do{make} GET-searches to the server with great volumes of the data. For this purpose there is a POST-search.


The client the part written on Javascript, should provide necessary functionality for a safe exchange with the server and give methods for data exchange by any of the set forth above ways. The server part should process the entrance data, and on the basis of them to generate the new information (for example, working with a database), and to give her  back to the client. For example, for search of the information from the server it is possible to use usual GET-search with transfer of several and small parameters on the size, and for updating the information, or the POST-search as he allows to pass great volumes of the data is required to use additions of the new information already.


As it has already been said, AJAX uses asynchronous data transfer. It means, that while there is a data transfer, the user can make other actions necessary for him. At this time it is necessary to notify the user that there is any data exchange, differently the user will think, that there was something not that and can leave{abandon} a site, or repeatedly call "hanged", in his  opinion, function. Indication during data exchange in application Web 2.0 plays very important role: visitors could not get used yet to such ways of updating of page.


The answer from the server can be not only XML as follows from the name of technology. Besides XML, it is possible to receive the answer as the usual text, or JSON (Javascript Object Notation). If the answer has been received by a plain text it{he} can be deduced{removed} at once in the container on page. At reception of the answer as XML, usually there is a processing received XML the document on the party  of the client and transformation of the data to (X) HTML. At reception of the answer in format JSON the client should execute only the received code (function Javascript ` and eval) for reception of high-grade object Javascript. But here it is necessary to be cautious and to take into account that fact, that with use of this technology the nocuous code can be transferred{handed}, therefore before performance of the code received from the server it is necessary to check up and process it  carefully. There is such practice as "single" search at which any answer from the server does not come, the data on the party  of the server only change.


In different browsers the given object possesses different properties, but as a whole he coincides.

Methods of object XMLHttpRequest


Notice, that names of methods are written down in the same style (Camel-style), as other functions Javascript. be close{attentive} at their use.


abort () - a cancellation of the current search to the server.


getAllResponseHeaders () - to receive all headings of the answer from the server.


getResponseHeader ("imja_zagolovka") - to receive ukazanyj heading.


open ("tip_zaprosa", "URL", "asynchronous", "imja_pol`zovatelja", "password") - initialization of search to the server, the instruction{indication} of a method of search. Type of search and URL - obligatory parameters. The third argument - bulevo value. Usually it is always underlined true or it is not underlined in general (by default - true). The fourth and fifth arguments are used for autentifikacii (it is very unsafe to store{keep} the data about autentifikacii in a script as any user can see a script).


send ("contents") - to send HTTP search about the server and to receive the answer.


setRequestHeader ("imja_zagolovka", "value") - to establish values of heading of search.

Properties of object XMLHttpRequest


onreadystatechange - one of the most important properties of object XMLHttpRequest. With the help of this property it is set obrabotchik which is caused every time at change of the status of object.


readyState - the number designating the status of object.


responseText - performance of the answer of the server as the usual text (line).


responseXML - the object of the document compatible with DOM, received from the server.


status - a status of the answer from the server.


statusText - text performance of a status of the answer from the server.


Follows more in detail rasmmotret` property readyState:

?         0 - the Object is not initialized.

?         1 - the Object loads the data.

?         2 - the Object has loaded the data.

?         3 - Ob``ek it is not completely loaded, but can cooperate with the user.

?         4 - the Object is completely initialized; the answer from the server is received.


Leaning{Basing} on a status of readiness of object it is possible to present the visitor the information on at what stage there is a process of data exchange with the server and, probably, to notify it  on it visually.

Creation of object XMLHttpRequest


As creation of the given object for each type of a browser - unique process was already spoken above.


For example, for creation of object in Gecko-compatible browsers, Konqueror ` e and Safari, it is necessary to use the following expression:



var Request = new XMLHttpRequest ();


And for Internet Explorer ` and the following is used:



var Request = new ActiveXObject (" Microsoft. XMLHTTP ");


Or



var Request = new ActiveXObject (" Msxml2. XMLHTTP ");


Now, to achieve krossbrauzernosti, it is necessary to combine all functions in one:



function CreateRequest ()

{

var Request = false;


if (window. XMLHttpRequest)

{

// Gecko-compatible browsers, Safari, Konqueror

Request = new XMLHttpRequest ();

}

else if (window. ActiveXObject)

{

// Internet explorer

try

{

Request = new ActiveXObject (" Microsoft. XMLHTTP ");

}

catch (CatchException)

{

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

}

}


if (! Request)

{

alert (" It is impossible to create XMLHttpRequest ");

}


return Request;

}


After all it it is possible to create the given object and does not worry for serviceability on popular browsers. But to create object it is possible in different places. If to create it  it is global, during the certain moment of time one search to the server will be possible  only. It is possible to create object every time as there is a search to the server (it almost completely will solve a problem).

Search to the server


The algorithm of search to the server looks so:

?         Check of existence XMLHttpRequest.

?         Initialization of connection with the server.

?         A parcel{sending} zaprsa to the server.

?         Processing the received data.


For creation of search to the server we shall create small function which on functionality will unite in itself functions for GET and POST searches.



/*

Function of a parcel{sending} of search to a file on the server

r_method - type of search: GET or POST

r_path - a way to a file

r_args - arguments of a kind a=1*b=2*c=3...

r_handler - function - obrabotchik of the answer from the server

*/

function SendRequest (r_method, r_path, r_args, r_handler)

{

// We create search

var Request = CreateRequest ();


// We check existence of search once again

if (! Request)

{

return;

}


// We appoint user obrabotchik

Request.onreadystatechange = function ()

{

// If data exchange is completed

if (Request.readyState == 4)

{

// We pass management obrabotchiku the user

r_handler (Request);

}

}


// We check, if it is required to make GET-search

if (r_method.toLowerCase () == "get" ** r_args.length> 0)

r_path + = "?" + r_args;


// We initialize connection

Request.open (r_method, r_path, true);


if (r_method.toLowerCase () == "post")

{

// If it is POST-search


// We establish{install} heading

Request.setRequestHeader ("Content-Type", " application/x-www-form-urlencoded; charset=utf-8 ");

// We send search

Request.send (r_args);

}

else

{

// If it is GET-search


// We send zero - search

Request.send (null);

}

}


To create search it became much easier. For an example we shall write function which will receive contents of a file on the server and to deduce  it  in the container.



function ReadFile (filename, container)

{

// We create function obrabotchik

var Handler = function (Request)

{

document.getElementById (container) .innerHTML = Request.responseText;

}


// We send search

SendRequest ("GET", filename, " ", Handler);


}


Thus there is an interaction to the server.