Now on the Internet there is a very active development (and even use) of new technologies. One of these technologies is
AJAX .
What is AJAX?
AJAX is an abbreviation of Asynchronous Javascript and XML. In fact, AJAX is not a new technology, since both Javascript and XML have been around for quite some time, and AJAX is a synthesis of the designated technologies. AJAX is most often associated with the term Web 2.0 and presented as the latest Web application.
')
When using AJAX, there is no need to refresh the entire page each time, since only its specific part is updated. This is much more convenient, since it does not have to wait long, and is more economical, since not everyone has unlimited Internet. True in this case, the developer needs to ensure that the user is aware of what is happening on the page. This can be implemented using the download indicators, text messages that the data is being communicated with the server. You must also understand that not all browsers support AJAX (older versions of browsers and text browsers). Plus Javascript can be disabled by the user. Therefore, one should not abuse the use of technology and resort to alternative methods of presenting information on the Web site.
Summarize the advantages of AJAX:
- The ability to create a convenient Web-interface
- Active user interaction
- Partial page reload, instead of full
- The convenience of use
AJAX uses two methods of working with a web page: changing a web page without reloading it, and dynamically accessing the server. The second can be done in several ways, in particular, XMLHttpRequest, which we will talk about, and the use of the hidden frame technique.
Data exchange
In order to exchange data, an XMLHttpRequest object must be created on the page, which is a kind of intermediary between the User Browser and the server (Fig. 1). Using XMLHttpRequest, you can send a request to the server, as well as get a response in the form of various kinds of data.

You can communicate with the server in two ways. The first method is a GET request. In this request, you access the document on the server, passing it the arguments through the URL itself. At the same time, on the client side, it will be logical to use the Javascript function escape to prevent some data from interrupting the request.
It is not recommended to make GET requests to the server with large amounts of data. There is a POST request for this.
The client part written in Javascript should provide the necessary functionality for a secure exchange with the server and provide methods for exchanging data using any of the above methods. The server part must process the input data and, based on it, generate new information (for example, working with the database) and give it back to the client. For example, to request information from the server, you can use a regular GET request with transmission of several and small in size parameters, and to update the information or add new information you will need to use the POST request, since it allows you to transfer large amounts of data.
As already mentioned, AJAX uses asynchronous data transfer. This means that while data is being transmitted, the user can perform other actions that he needs. At this time, you should notify the user that there is some kind of data exchange, otherwise the user will think that something wrong has happened and may leave the site, or re-call the function that he or she has hung. Indication during data exchange in a Web 2.0 application plays a very important role: visitors could still not get used to such methods of updating the page.
The response from the server may not only be XML, as the name of the technology suggests. In addition to XML, you can get the answer in plain text, or JSON (Javascript Object Notation). If the answer was received in plain text, then it can be immediately displayed in a container on the page. When a response is received in the form of XML, the received XML document is usually processed on the client side and the data is converted to (X) HTML. When receiving a response in JSON format, the client only has to execute the received code (the Javascript function of eval) to get the full Javascript object. But here you need to be careful and take into account the fact that using this technology can be transmitted malicious code, so before executing the code received from the server, it should be carefully checked and processed. There is a practice such as “idle” request, in which no response from the server comes, only the data on the server side changes.
In different browsers, this object has different properties, but in general it is the same.
XMLHttpRequest object methods
Notice that method names are written in the same style (Camel-style) as other Javascript functions. Be careful when using them.
abort () - cancel the current request to the server.
getAllResponseHeaders () - get all response headers from the server.
getResponseHeader (“header_name”) - get the
specified header.
open ("request_type", "URL", "asynchronous", "username", "password") - initiate a request to the server, specify the method of the request. Request type and URL are required parameters. The third argument is a boolean value. It is usually always true or not specified at all (true by default). The fourth and fifth arguments are used for authentication (it is very insecure to store authentication data in a script, since any user can see the script).
send ("content") - send an HTTP request to the server and receive a response.
setRequestHeader (“header_name”, “value”) - set the values of the request header.
XMLHttpRequest object properties
onreadystatechange is one of the most important properties of the XMLHttpRequest object. Using this property, a handler is set that is called whenever the status of an object changes.
readyState is a number indicating the status of the object.
responseText - representing the server response in plain text (string).
responseXML is a document object that is compatible with the DOM received from the server.
status - the status of the response from the server.
statusText is a textual representation of the response status from the server.
It is necessary to examine in more detail the readyState property:
- 0 - The object is not initialized.
- 1 - Object loads data.
- 2 - The object has loaded its data.
- 3 - The object is not fully loaded, but can interact with the user.
- 4 - The object is fully initialized; received a response from the server.
It is based on the state of readiness of the object that it is possible to provide the visitor with information on what stage the process of data exchange with the server is and, possibly, to notify him visually.
Creating an XMLHttpRequest Object
As mentioned above, the creation of this object for each type of browser is a unique process.
For example, to create an object in Gecko-compatible browsers, Konqueror and Safari, you need to use the following expression:
var Request = new XMLHttpRequest();
And for Internet Explorer, the following is used:
var Request = new ActiveXObject("Microsoft.XMLHTTP");
Or
var Request = new ActiveXObject("Msxml2.XMLHTTP");
Now, in order to achieve cross-browser compatibility, it is necessary to add all the functions into one:
function CreateRequest() { var Request = false; if (window.XMLHttpRequest) { //Gecko- , 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(" XMLHttpRequest"); } return Request; }
After all this, you can create this object and does not worry about performance on popular browsers. But you can create an object in different places. If you create it globally, then at a certain moment in time only one request to the server will be possible. You can create an object whenever a request to the server occurs (this will almost completely solve the problem).
Request to server
The server request algorithm looks like this:
- Check for the existence of XMLHttpRequest.
- Initialization of connection with the server.
- Sending request to server.
- Processing the data.
To create a request to the server, we will create a small function that will combine functions for GET and POST requests by functionality.
function SendRequest(r_method, r_path, r_args, r_handler) { // var Request = CreateRequest(); // if (!Request) { return; } // Request.onreadystatechange = function() { // if (Request.readyState == 4) { // r_handler(Request); } } //, GET- if (r_method.toLowerCase() == "get" && r_args.length > 0) r_path += "?" + r_args; // Request.open(r_method, r_path, true); if (r_method.toLowerCase() == "post") { // POST- // Request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); // Request.send(r_args); } else { // GET- // - Request.send(null); } }
Making a request has become much easier. For example, we write a function that will receive the contents of a file on the server and output it to a container.
function ReadFile(filename, container) { // var Handler = function(Request) { document.getElementById(container).innerHTML = Request.responseText; } // SendRequest("GET",filename,"",Handler); }
This is how the interaction with the server occurs.
Response processing
In the previous example, we made the server request function. But it is, in fact, unsafe, since we do not process the state of the object and the state of the response from the server.
Let's add our code so that it can display a visual notification of the download process.
... Request.onreadystatechange = function() { // if (Request.readyState == 4) { // r_handler(Request); } else { // } } ...
As you already know, the XMLHttpRequest object lets you know the status of the response from the server. Take advantage of this opportunity.
... Request.onreadystatechange = function() { // if (Request.readyState == 4) { if (Request.status == 200) { // r_handler(Request); } else { // } } else { // } } ...
Answer options from the server
There are several types of data from the server:
If you receive plain text, you can immediately send it to the container, that is, to the conclusion. When retrieving data as XML, you must process the data using DOM functions, and present the result using HTML.
JSON is the Javascript object notation. With its help, you can represent an object as a string (here you can make an analogy with the serialization function). When you receive JSON data, you must execute it in order to get a full-fledged Javascript object and perform the necessary operations with it. Remember that such data transfer and execution are not secure. You have to keep track of what comes to execution.
Sample JSON Code:
{ "data": { "misc": [ { "name" : "JSON- ", "type" : " 1" }, { "name" : "JSON- ", "type" : " 2" } ] } }
Upon receipt of such a code, we perform the following action:
var responsedata = eval("(" + Request.responseText + ")")
After this code is executed, the
responsedata object will be available to you.
Work with server programming languages
Such work is no different from the usual. For examples, I'll take PHP as the server language. In the client part, nothing has changed, but the server part is now represented by a PHP file.
By tradition, let's start with a greeting to our wonderful world:
echo "Hello, World!";
When accessing this file, the client will return the string Hello, World. As you understand, this represents the broadest possibilities for building applications. Based on passing arguments to the server using XMLHttpRequest, you can make output parameterization, thereby providing extensive Web application functionality.
In addition to PHP, you can use any other server programming language.
Related Literature
The article is written to tell newbies about the work of AJAX from the inside. If it seems to you that something is written inaccurately or incorrectly, please correct me in order to create a worthy article together.
Of course, if there is an opportunity, it is worth using existing frameworks, I think. But to know "how it works" is still necessary.