Ajax technology, its purpose and operating principle. WEB design AJAX technology - learning Ajax using an example

All novice webmasters sooner or later encounter a problem dynamic change data on an HTML page, and without reloading this very page. And, of course, JavaScript comes to the rescue, but it does not know how to access the server and receive data without reloading the page, but AJAX can do it, which is what we will talk about today.

Note. If you don't know JavaScript basics, and you can’t understand simple JavaScript code, I advise you, first, to read these articles “JavaScript for Beginners – Simple Examples” and “JavaScript – Example of Extending a Registration Form”, because without knowledge of JavaScript, learning AJAX is pointless!

What is AJAX?

AJAX ( Asynchronous JavaScript and XML) - asynchronous JavaScript and XML, this is a mechanism for interacting with the server, through which data is exchanged with this server without reloading the entire page. An AJAX request can be not only asynchronous, but also simply synchronous, but such requests are rarely used. Since with such requests the browser freezes until a response is received from the server, in contrast to an asynchronous request, in which a request is sent and the user can do whatever he wants on the page, and when a response is received from the server, the handler will work and changes will appear on the page. We will learn how to send synchronous and asynchronous requests in the examples below.

What is AJAX for?

And the first thing that comes to mind is, of course, fast and user-friendly interface for user. In other words, the user likes it when everything works quickly for him and he doesn’t need to make unnecessary movements; besides, to make it all look beautiful, JavaScript and AJAX do an excellent job with this.

The second thing I would like to note is the reduction in server load. Since when the page is reloaded or when opening new page, the load on the server is much greater as opposed to requesting and receiving specific data. Another way to explain this is that when a page is opened, all server scripts that are needed to display this page are processed, and when a request is made via ajax, only one script is processed that is needed for processing specific request, and the output to the screen occurs using JavaScript, which is a client technology.

Thirdly, this, of course, reduces traffic, since the weight of the entire page is much larger than the small piece of data that you will receive through an ajax request.

Disadvantages of AJAX

I cannot help but note the minor shortcomings of this mechanism. Firstly, JavaScript and AJAX work on the client side, so in order for everything to work, you need to enable JavaScript support in the browser, it can simply be turned off for security reasons and your creation simply may not work at all.

Secondly, it can be noted that when using ajax, the received data is not indexed by search engines and, of course, you cannot bookmark it in the browser.

AJAX example

Enough theory, let's move on to practice. I’ll say right away that ajax is not difficult, and if you understand JavaScript, then understanding ajax will be very simple, even easier than JavaScript!

And I'll start with the fact that all ajax is built on the XMLHttpRequest object, which has several properties and several methods that are easy to learn and remember. The XMLHttpRequest object is a kind of mini-browser on behalf of which a request will be sent to the server script.

The whole mechanism begins with the creation of this object, and it can be created in different ways, in old browsers this is done in one way, and in all new browsers in a different way. If suddenly you do not plan to use ajax on older browsers, for example, you are creating an ajax application for corporate network, in which they are installed modern browsers You can safely create this object with one line:

Var request = new XMLHttpRequest();

where, in the request variable, our object will be stored.

But if your application can be used in older browsers, then it is better to use universal method creating this object, for example, I like this method:

Function getXmlHttpRequest() ( if (window.XMLHttpRequest) ( try ( return new XMLHttpRequest(); ) catch (e)() ) else if (window.ActiveXObject) ( try ( return new ActiveXObject("Msxml2.XMLHTTP"); ) catch (e)() try ( return new ActiveXObject("Microsoft.XMLHTTP"); ) catch (e)() ) return null )

To create an XMLHttpRequest object, we simply call the getXmlHttpRequest function, which will return us the desired object.

The object has been created, now you can write JavaScript code that will generate a request to the server and process the data received from the server.

In order for our lesson to be complete, we will need a small server-side script, I will use server-side language PHP programming, and our script will simply return current time on the server. Let's call it mytime.php, its code:

mytime.php code:

Here I think everything is clear, we check the parameter that came to us GET method, i.e. MyTime, and if the parameter really came to us, then we return the current time on the server. When developing an ajax application on a server script, I advise you to do more checks, since an ajax request can be faked. You can do the following checks, for example:

  • you can additionally send the X-REQUESTED-WITH header and check it on the server handler;
  • also add referrer check, i.e. where the request came from;
  • You can also check using sessions.

index.php code:

//function for creating an XMLHttpRequest object function getXmlHttpRequest())( if (window.XMLHttpRequest) ( try ( return new XMLHttpRequest(); ) catch (e)() ) else if (window.ActiveXObject) ( try ( return new ActiveXObject("Msxml2 .XMLHTTP"); ) catch (e)() try ( return new ActiveXObject("Microsoft.XMLHTTP"); ) catch (e)() ) return null; ) function serverTime())( // XMLHttpRequest object var request = getXmlHttpRequest (); /*onreadystatechange property is an event handler that reacts to any change in this object*/ request.onreadystatechange = function ()( /*readyState property - object state 0 - not initialized, 1 - open, 2 - sending data, 3 - receiving data, 4 - data loaded, I recommend using only 4*/ if (request.readyState == 4) ( /*status property is the HTTP status of the response: 200-OK, 404-Not Found*/ if (request.status == 200) ( var result = document.getElementById("MyId"); // Reading the response result.firstChild.nodeValue = request.responseText; // Output to the screen ) else document.write("An error occurred. Refresh the page" ) ) / / Server script address var url = "mytime.php?MyTime"; /* Request to the server, true means that it is asynchronous request if it were false, then this is a synchronous request */ request.open("GET", url, true); request.setRequestHeader("Content-type", "charset=utf8"); request.send(null); // send data)

Here are two files ( mytime.php and index.php), with which you can easily check the operation of ajax, the code of these files is presented above.

By the way, in the above example we have used GET method to transfer data, there are many ways to transfer data and all the main data is transferred using POST method. Let's rewrite our serverTime function so that it transmits data using the post method, this is very easy to do since you only need to change a few lines.

Code of the serverTime function with passing parameters using the post method:

Function serverTime())( var request = getXmlHttpRequest(); request.onreadystatechange = function ()( if (request.readyState == 4) ( if (request.status == 200)( var result = document.getElementById("MyId" ); result.firstChild.nodeValue = request.responseText; ) else document.write("An error occurred. Refresh the page"); var url = "mytime2.php";//change the server handler address var data = "MyTime= 1"; // set the parameters request.open("POST", url, true); // specify the post method // send two headers: data type and data size request.setRequestHeader("Content-Type", "application/x -www-form-urlencoded"); request.setRequestHeader("Content-Length", data.length); request.send(data); // send data, insert a variable with parameters instead of null)

Don't forget to change the server handler so that it checks the data received using the post method. Change the line isset($_GET["MyTime"] to isset($_POST["MyTime"] and everything will work exactly the same as with GET.

As you noticed, ajax is not at all a complicated thing, although these are just the basics, but still, if you understand, for example, JavaScript, then mastering ajax will not be a problem.

In today's lesson we covered only the basics, there is still something to learn in ajax (although not much), for example, transferring complex data, etc., but I hope this lesson helped you learn what ajax is and in the next lessons we will continue study this mechanism of interaction with the server!


Our life is impermanent. Everything in this world evolves and changes. Including virtual reality. And one of the words that these changes are associated with is AJAX. Not only web programmers, but also ordinary users have already heard about AJAX. What really lies behind this magical abbreviation? How to use this on your site? I will try to answer these questions in this article.

I first heard about AJAX in the spring of this year. I immediately became interested in this technology, and, as it should be in such cases, I went looking for articles that could answer the questions I had: “What is it? How does it work? And what are the advantages? What additionally needs to be installed on the server /client for working with AJAX? How can I use this on my website? After reading a dozen articles, I received an answer only to the first two questions, but I couldn’t find an answer to the rest anywhere. And only after reading several publications in English did I finally understand what was happening. This prompted me to write this material.

First of all, the article is addressed to trained people, program writers for the Internet and familiar with terms such as “object”, “method”, “properties”. However, it may also be partially useful for those who are simply interested in this issue. The list of references contains the necessary list of links, using which it is quite possible to master the technology “from scratch”.

In the course of the presentation, by the term “browser” we will understand the following browsers: Internet Explorer 5.0+, Safari 1.3 and 2.0+, Netscape 7+, Opera 8.5+, Mozilla Firefox (plus means this version and newer). If we talk about other versions, this will be mentioned separately. "What is it? How does it work and what are the advantages?"

To understand the benefits of AJAX, you need to know how web applications work today. And they work according to client-server technology(Fig. 1).

A user opens a page in a browser page. The page contains hyperlinks that lead to other pages. When you click on any of them, the browser sends a request URL to the server this link is associated with. If there is no server associated with that link in nature (for example, when typing the URL into address bar, you misspelled the resource name), or there are problems connecting to the Internet, then the browser will generate a page similar to the one shown in the picture (this is how it looks in Opera):

If a server exists, but the document specified in the request is not available on it, the server itself will create an HTML page describing the error. For example, this could be the well-known 404 error (document not found). Or, if everything is correct, the server will respond with a new page. In any case, a new page will be loaded into the browser new_page, even if only a couple of words have changed compared to the old one. Quite a significant disadvantage of this technology. In addition, the work is carried out in synchronous mode. That is, after the browser sends a request to the server, it expects a response from it, and until the response is received, it will not do anything. And sometimes the answer may take too long to load a new page. So long that the user may not wait for the page to load and simply close it. Therefore, web programmers resort to some tricks.

PROPERTIES:

readonly onreadystatechange function

Specifies a callback function that will be called every time a change is made. readyState property. Even though the function is called, parameters cannot be passed to it. But more on this later in the example.

readonly readyState integer

Request status. Can take values:
  • 0 - not uninitialized(uninitialized), method open() has not yet been called;
  • not called yet;
  • 2 - loaded(loaded), method send() was called and response headers/status (property status) received;
  • 3 - interactive(interactive), data is being received that is available through the property responseText;
  • 4 - completed(completed), in response to the request, not only all headers and status were received, but all data from the server was also received, the response is completed.

readonly responseText string

Server response in plain text. Read only.

readonly responseXML object

Server response as a DOM Document object. Used if the server response is a valid XML document. If the document is not correct, the data has not been received or has not yet been sent, then the property is NULL. Read only.

readonly status string

Response status. For example: 200 (OK), 404 (document not found), 503 (temporary server overload). METHODS:

void abort()

Aborts an HTTP request or receiving data. Clears all object properties that are assigned initial values. The method is useful in conjunction with a timer, when after a certain time has passed since the request (timed out), a response from the server has not been received.

string getAllResponseHeaders()

Returns all server response headers as a formatted string. Each new heading starts on a new line.

string getResponseHeader( string header)

Return a header named header.

void open( string method, string uri, [ boolean asynch])

Prepares a request at uri method method(POST or GET) indicating the asynch mode, asynchronous mode or not. As a result of calling the property readyState become equal to 1.

void send ( string data)

Initiates a request to the server. The request contains data data.

void setHeader( string header, string value)

Sets the header named header to value. Before you start using this method, be sure to call open()! "How can I use this on my website?"

Now that we have not only the necessary theoretical knowledge, but also an idea of ​​what AJAX practically relies on, we can start writing our own application. Next, I give one example from the moment the problem is formulated to its full implementation, in the form of an application, explaining some of the subtleties along the way.

So, we have a task: we need to implement a driver database (DB) for various devices. Moreover, the database is so large that there is no point in sending it to the client application and selecting from it using JavaScript. Due to a change in one value on the page, it is also undesirable to overload it. Personally, to implement this task I use server PHP scripts, and I use an XML file to implement the database.

I choose the following database structure:

Listing DB file data.xml: ATI 9600 128 DDR (128bit) ATI 9600 256 DDR (128bit) ATI 9600XT 256 DDR (128bit) ATI X800GTO 256 DDR (256 bit) ATI X1300 512 DDR (128bit) ATI X1300 256 DDR (128bit) NVidia 6 600 128 DDR (128bit ) NVidia 7800GS 256 DDR (256 bit) ATI X1300Pro 256 DDR (128bit) ATI X1600Pro 256 DDR (128bit) ATI X1800GTO 256 DDR (256bit) ATI X1600Pro 256 DDR (128bit) ATI X1900XT 512 DDR (256bit) ) NVidia 6600 Silencer 128 DDR ( 128bit) NVidia 6600GT 128 DDR (128bit) ATI X1900XT 512 DDR (256bit) ATI X1900XTX 512 DDR (256bit) ATI X800 SilentPipe 128 DDR(256bit) Nvidia 6600GT 128 DDR (128bit) NVidia 6600GT PassiveHeatsink 128 DDR (128bit) PCI-E ATI X550 128 DDR (128bit) PCI-E ATI X800GT Uniwise 256 DDR (256 bit) ATI X800GTO 256 DDR (128bit) Audigy 2 6.1 Audigy 2 ZS 7.1 X-Fi Platinum Audiophile 192 Revolution 5.1 Audiophile Audiophile Fast Track PIXMA iP 90 PIXMA PIXMA iP6600D Picture Mate 100 Stylus Color C48 Stylus Color C87U DeskJet 1280 DeskJet 5443 Photo Smart 385 Laser Shot LBP2900 Laser Shot LBP3300 ML 1615 ML 2015 LaserJet 1018 LaserJet 2420 LaserJet 2420DN 4200F 500F LiDE60 Perfection 1270 Perfection 3590 Perfection 4990 Bear Paw 2400CU Perfection 4990

How does a person search in this database? Most likely, it would go from the root element along the document tree until it found a link in the required branch or made sure that the driver for this device was not in the database. We will do the same, using XPath language expressions to find the desired node or set of nodes.

Listing the form for submitting data index.htm:

video cardsound cardprinter scanner

The form has two variables: path And flag. The first stores the requested path, which is sent to the server. Since there is already one element in the form, this variable already has an initial value. The second variable is used to indicate to the server script what to extract from the document specific element Device. In addition, the format of the data returned from the server will change.

Now let's look at the JS engine. All functions of the client part are collected in the script ajax.js: y = new Object(); function httpRequest() ( if (window.XMLHttpRequest) ( //creating an object for all browsers except IE requestObj = new XMLHttpRequest(); ) else if (window.ActiveXObject) ( //for IE requestObj = new ActiveXObject("Msxml2.XMLHTTP "); if (!requestObj) ( requestObj = new ActiveXObject("Microsoft.XMLHTTP"); ); ); ); function sendRequest (url,data) ( httpRequest(); //define the call-back function requestObj.onreadystatechange = responseServer; //preparing to send data, readyState=1 requestObj.open("POST",url,true); /* T .since the data is sent by the POST method, the server needs to send a header informing it about this */ requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); sending data to the server requestObj.send(data); function responseServer() ( if (requestObj.readyState == 4) ( var status = requestObj.status; if (status == 200) ( addSelect(y); ) else if (status == 400) ( alert("Invalid request "); ) else if (status == 500) ( alert("Internal error on the server"); ) else if (status == 503) ( var time = requestObj.getResponseHeader("Retry-After")*1000; alert ("The server is overloaded. The request will be repeated in: "+time+" seconds"); setTimeout(sendRequest(url,path),time ) else ( alert("Server error"); ); function sendData(obj) ( var Elpath = document.form.path; var url = "index.php"; if (document.form.flag.value == "0") ( var path = Elpath.value + "/" + obj.value; ) else ( var path = Elpath.value + "/Device["" + obj.value + ""]"; /* using the GET method we send information to the server script that a specific Device element is needed */ url = "index.php?flag=1"); //assign variable shape path value of the current request Elpath.value = path; //encode the transmitted string path path = "path="+encodeURIComponent(path); y = obj; sendRequest(url,path); ); function addSelect(obj) ( //server response in plain text var docTEXT = requestObj.responseText; obj.setAttribute("disabled",true); //create a div element var div = document.createElement("div"); / /add the server response to the div div.innerHTML = docTEXT; //add a div with the server response to the document tree document.form.appendChild(div); function reset() ( document.form.path.value="//Devices"; document.form.flag.value="0"; var NodeListDiv = document.form.getElementsByTagName("div"); var length = NodeListDiv.length; if (length > 1) { while (NodeListDiv != undefined) { document.form.removeChild(NodeListDiv); }; }; document.form.Devices.removeAttribute("disabled"); };!}

As I already said, in the property function onreadystatechange parameters cannot be passed. More precisely, you cannot pass parameters that are objects. Therefore, at the very beginning, we create a variable in which we will store a link to the object that called the function. Since this variable is in the global variable visibility zone, it can be accessed from any part of the program. This is currently the most sensible way to pass call-back parameters to a property function onreadystatechange object.

Now let’s take a step-by-step look at how the engine works.

When an event occurs onblur(element select lost focus) function is called sendData(), which prepares POST data to submit a request. In addition, it generates an XPath expression depending on the value of the variable flag=0(For example, //Devices/VideoCards) or flag=1(For example, //Devices/VideoCards/AGP/Sapphire/Device["ATI 9600XT 256 DDR (128bit)"]).

Next we call the function sendRequest(), into which we pass the URL of the server script, as well as type variable a line containing ready-made POST data. And first of all we create XMLHttpRequest an object, a link to which is stored in a variable requestObj. Function httpRequest() is cross-browser and will work in all browsers.

Once upon a time calling a function httpRequest() I did it immediately when loading the page via and didn't create anymore XMLHttpRequest object. But as it turns out, this works for all browsers except IE, which requires creating a new object each time. Therefore, this function is called every time before sending data.

After sending the data, the browser waits for a response from the server. Every time a property changes readyState the function will be called responseServer(). If the response status comes with the code "200" (everything is fine), then the function will be called addSelect(), which will add the resulting data to the DOM of the current document. All browsers will wait for a response from the server. However, after some time (time-out) the XMLHttpRequest.readyState = 4 and stop waiting for a response from the server. For example, for Opera the timeout value is 10 seconds. Using other statuses, you can add an error handler to the engine in server responses.

Function addSelect() adds another node to the DOM of the current document DIV, into which it places the response from the server. One might wonder why the property is used responseText, not responseXML? Someone will definitely have a desire, using this property, to import the server response (and the server script sends an XML document in response) directly into the DOM of the document. I had the same desire. I wanted to import the root element of the sent XML file and all its descendants by method importNode. But the browser imported the element without children, even though the second parameter of this method was set to true: importNode(Object importedNode,true). Therefore, the inaccurate implementation of this method precludes its use for now.

An equivalent solution was found using innerHTML element method.

This is where the work of the client part ends. Remaining unexamined function reset() is designed to return the DOM of the document to its original form. The same can be achieved by refreshing the page using F5, but the AJAX engine is precisely written in order to avoid page reloading. Therefore, all elements added to the document by the script must also be removed from it by the script.

In response to the request, the server script generates XML data of the form: childrenElementName_1 .... childrenElementName_1

If the requested node has the name Device, then plain formatted text is returned. The server script is written in PHP V5 and will not work for more than earlier versions this interpreter, since the extension for working with DOM was introduced into this language only in the fifth version, and replaced the DOM XML extension, the interface of which did not comply with the specification. Now let's look at the server script code.

File listing index.php: load("data.xml"); //create an XPath object $DOMXPath = new DOMXPath($doc); $DOMNodeList = $DOMXPath -> query($_POST); //according to the request, extract the required element $DOMNode = $DOMNodeList -> item(0); //create an XML document object $replyXML = new DOMDocument("1.0", "windows-1251"); /* if flag is not equal to one , which means the current element is not a Device element and it is necessary to find all descendant elements of the current DOMNode element */ if ($_GET != 1) ( //get a list of all descendants of the element $childNodes = $DOMNode -> childNodes; /* Since descendants can be not only elements, but also nodes, then create an index array that contains only descendant elements */ foreach ($childNodes as $Node) ( if ($Node->nodeType == 1) ( $arrayNodes = $Node; ); ); //create the root element of the XML document $root = $replyXML->createElement("select"); $optgroup = $replyXML->createElement("optgroup"); /* if the descendant elements are not Device, then set attributes for the root element and its child element optgroup */ if ($arrayNodes -> nodeName != "Device") ( $root->setAttribute("name",$DOMNode->nodeName); $AttributeNode = $arrayNodes-> getAttributeNode("title"); $optgroup->setAttribute("label",$AttributeNode->value); $root->setAttribute("onblur","sendData(this)"); else ( /* otherwise create an attribute with JS code that will assign the value "1" to a variable in the flag form */ $root->setAttribute("onblur", "document.form.flag.value=1;sendData(this);"); ); /* loop creating new option elements for each descendant element; as many children as there are elements */ foreach ($arrayNodes as $Node) ( $option = $replyXML->createElement("option"); $setNode = $Node->nodeName; if ($Node->nodeName == " Device") ( $setNode = $Node->nodeValue; ); $option-> nodeValue = $setNode; $option->setAttribute("value",$setNode); $optgroup->appendChild($option); ); //insert the resulting elements into the XML document $replyXML->appendChild($root); $root->appendChild($optgroup); /* if flag=1, then the current element is a Device element; descendant elements are not needed, but the attributes of the current element are needed */ ) else ( //create a root element $root = $replyXML->createElement("pre"); $DOMText = new DOMText(" OS URL"); $root - > appendChild($DOMText); $NamedNodeMapAttr = $DOMNode->attributes; $i = 0; /* a loop that finds all attributes of the Device element and for each attribute creates a row with the contents of the link */ while (($NodeAttr = $NamedNodeMapAttr ->item($i)) != null) ( if ($NodeAttr->name != "id") ( $DOMText = new DOMText(" $NodeAttr->name "); $DOMElement = $replyXML->createElement ("a"); $DOMElement -> setAttribute("href",$NodeAttr->value); $DOMElement -> nodeValue = $NodeAttr->value; $root -> appendChild($DOMText); ($DOMElement); $i++; $NamedNodeMapAttr->item($i); //send the response to the client echo $replyXML->saveHTML(); ? >

Nowadays there is a very active development (and even use) of new technologies on the Internet. One such technology is AJAX.

What is AJAX?

AJAX is an acronym that stands for Asynchronous Javascript and XML. In fact, AJAX is not new technology since both Javascript and XML have been around for quite some time now for a long time, and AJAX is a synthesis of the indicated technologies. AJAX is most often associated with the term Web 2.0 and is touted as the latest Web application.

At using AJAX there is no need to refresh the entire page each time, since only a specific part of it is updated. This is much more convenient, since you don’t have to wait long, and 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 loading indicators, text messages that data is being exchanged 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 presentation of information on the website.

Let's summarize the advantages of AJAX:

  • Ability to create a convenient Web interface
  • Active user interaction
  • Ease of use

AJAX uses two methods of working with a web page: changing the Web page without reloading it, and dynamically contacting the server. The second can be done in several ways, in particular, XMLHttpRequest, which we will talk about, and using 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’s Browser and the server (Fig. 1). Using XMLHttpRequest, you can send a request to the server and also receive a response in the form of various types of data.

There are two ways to exchange data with the server. The first method is a GET request. In this request, you access a document on the server, passing it arguments through the URL itself. In this case, on the client side it would be logical to use the Javascript escape function so that some data does not interrupt the request.

The client part, written in Javascript, must provide the necessary functionality for secure exchange with the server and provide methods for exchanging data in any of the above ways. The server part must process the input data, and based on it, generate new information (for example, working with a database), and send it back to the client. For example, to request information from the server, you can use a regular GET request passing several and small parameters, and to update information or add new information You will need to use a POST request, since it allows you to transfer large amounts of data.

As already mentioned, AJAX uses asynchronous data transfer. This means that while the data is being transferred, the user can perform other necessary actions. At this time, the user should be notified that some kind of data exchange is taking place, otherwise the user will think that something wrong has happened and may leave the site, or re-call the function that he thinks is “frozen.” The display during data exchange in a Web 2.0 application is very important role: Visitors might not yet be used to this way of updating the page.

The response from the server can be not only XML, as the name of the technology suggests. In addition to XML, you can receive the response in plain text, or JSON (Javascript Object Notation). If a response was received in plain text, then it can be immediately displayed in a container on the page. When receiving a response 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 needs to execute the received code (Javascript's eval function) to obtain a full-fledged Javascript object. But here you need to be careful and take into account the fact that using this technology can be transferred malicious code, therefore, before executing the code received from the server, it should be carefully checked and processed. There is such a practice as a “idle” request, in which no response is received from the server, only the data on the server side is changed.

IN different browsers this object has different properties, but in general it is the same.

XMLHttpRequest object methods

Note that the method names are written in the same Camel-style as other Javascript functions. Be careful when using them.

abort() - cancels 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","user_name","password") - initializing a request to the server, specifying the request method. Request type and URL are required parameters. The third argument is a boolean value. Usually true is always specified or not specified at all (the default is true). The fourth and fifth arguments are used for authentication (it is very unsafe to store authentication data in a script, since the script can be viewed by any user).

send("content") - send an HTTP request to the server and receive a response.

setRequestHeader("header_name","value") - set the request header values.

Properties of the XMLHttpRequest object

onreadystatechange is one of the most important properties of the XMLHttpRequest object. Using this property, a handler is specified that is called whenever the status of an object changes.

readyState is a number indicating the status of the object.

responseText — representation of the server response as plain text (string).

responseXML is a DOM-compatible document object received from the server.

status — status of the response from the server.

statusText — text representation of the status of the response from the server.

You should take a closer look at the readyState property:

  • 0 — The object is not initialized.
  • 1 - The object is loading data.
  • 2 — The object has loaded its data.
  • 3 - The object is not fully loaded, but can be interacted with by the user.
  • 4 — The object is fully initialized; a response was received from the server.

It is based on the state of readiness of the object that you can provide the visitor with information about what stage the process of data exchange with the server is at and, possibly, notify him about this visually.

Creating an XMLHttpRequest object

As mentioned above, creating this object for each browser type 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");

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

Now, to achieve cross-browser compatibility, you need to combine all the functions into 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("Cannot create XMLHttpRequest"); ) return Request; )

After all this, you can create this object and 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 point in time only one request to the server will be possible. You can create an object every time a request is made to the server (this will almost completely solve the problem).

Request to the server

The server request algorithm looks like this:

  • Checking the existence of XMLHttpRequest.
  • Initializing a connection to the server.
  • Sending a request to the server.
  • Processing of received data.

To create a request to the server, we will create a small function that will combine in functionality the functions for GET and POST requests.

/* Function for sending a request to a file on the server r_method - request type: GET or POST r_path - path to the file r_args - arguments like a=1&b=2&c=3... r_handler - function that handles the response from the server */ function SendRequest(r_method , r_path, r_args, r_handler) ( //Create a request var Request = CreateRequest(); //Check the existence of the request again if (!Request) ( return; ) //Assign a custom handler Request.onreadystatechange = function() ( // If the data exchange is completed if (Request.readyState == 4) ( //Pass control to the user handler r_handler(Request); ) ) //Check if you need to make a GET request if (r_method.toLowerCase() == "get" && r_args.length > 0) r_path += "?" + r_args; //Initialize the connection Request.open(r_method, r_path, true); if (r_method.toLowerCase() == "post") ( //If this is POST- request //Set the header Request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); //Send the request Request.send(r_args); ) else ( //If this is a GET request //Send a null request Request.send(null); ) )

Creating a request has become much easier. For example, let's write a function that will receive the contents of a file on the server and output it to a container.

function ReadFile(filename, container) ( //Create a handler function var Handler = function(Request) ( document.getElementById(container).innerHTML = Request.responseText; ) //Send the request SendRequest("GET",filename,"", Handler);

This is how interaction with the server occurs.

Processing the response

In the previous example, we made a request function to the server. But it is essentially unsafe, since we do not process the state of the object and the state of the response from the server.

Let's add to our code so that it can display a visual notification about the loading process.

Request.onreadystatechange = function() ( //If the data exchange is completed if (Request.readyState == 4) ( //Pass control to the user handler r_handler(Request); ) else ( //Notify the user about the download) ) ...

As you already know, the XMLHttpRequest object allows you to know the status of the response from the server. Let's take advantage of this opportunity.

Request.onreadystatechange = function() ( //If data exchange is completed if (Request.readyState == 4) ( if (Request.status == 200) ( //Pass control to the user handler r_handler(Request); ) else ( // We notify the user about the error that occurred) ) else ( //Notify the user about the download ) ) ...

Server response options

You can receive several types of data from the server:

  • Plain text
  • If you receive plain text, then you can immediately send it to the container, that is, to the output. When receiving data as XML, you must process the data using DOM functions, and present the result using HTML.

    JSON is Javascript object notation. With its help, you can represent an object as a string (here you can give an analogy with the serialization function). When receiving JSON data, you must execute it to get a complete Javascript object and perform the necessary operations with it. Please be aware that such data transmission and execution are not secure. You have to keep track of what comes in for execution.

    AJAX is an acronym that stands for Asynchronous Javascript and XML. In fact, AJAX is not a new technology, since both Javascript and XML have been around for quite a long time, and AJAX is a synthesis of the designated technologies. AJAX is most often associated with the term Web 2.0 and is touted as the latest Web application.

    When using AJAX, there is no need to refresh the entire page each time, since only a specific part of it is updated. This is much more convenient, since you don’t have to wait long, and more economical, since not everyone has unlimited Internet. True, in this case, the developer needs to make sure that the user is aware of what is happening on the page. This can be implemented using loading indicators and text messages indicating that data is being exchanged 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 a Web site.

    Let's summarize the advantages of AJAX:

    • Ability to create a convenient Web interface
    • Active user interaction
    • Ease of use
    AJAX uses two methods of working with a web page: changing the Web page without reloading it, and dynamically contacting the server. The second can be done in several ways, in particular, XMLHttpRequest, which we will talk about, and using 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’s Browser and the server (Fig. 1). Using XMLHttpRequest, you can send a request to the server and also receive a response in the form of various types of data.

    There are two ways to exchange data with the server. The first method is a GET request. In this request, you access a document on the server, passing it arguments through the URL itself. In this case, on the client side it would be logical to use the Javascript escape function so that some data does not interrupt the request.

    The client part, written in Javascript, must provide the necessary functionality for secure exchange with the server and provide methods for exchanging data in any of the above ways. The server part must process the input data, and based on it, generate new information (for example, working with a database), and send it back to the client. For example, to request information from the server, you can use a regular GET request with the transfer of several small parameters, but to update information or add new information, you will need to use a POST request, since it allows you to transfer large amounts of data.

    As already mentioned, AJAX uses asynchronous data transfer. This means that while the data is being transferred, the user can perform other necessary actions. At this time, the user should be notified that some kind of data exchange is taking place, otherwise the user will think that something wrong has happened and may leave the site, or re-call the function that he thinks is “frozen.” Indication during communication in a Web 2.0 application plays a very important role: visitors may not yet be accustomed to this way of updating the page.

    The response from the server can be not only XML, as the name of the technology suggests. In addition to XML, you can receive the response in plain text, or JSON (Javascript Object Notation). If the response was received in simple text, then it can be immediately displayed in a container on the page. When receiving a response 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 needs to execute the received code (Javascript's eval function) to obtain a full-fledged Javascript object. But here you need to be careful and take into account the fact that malicious code can be transmitted using this technology, so before executing the code received from the server, you should carefully check and process it. There is such a practice as a “idle” request, in which no response is received from the server, only the data on the server side is changed.

    In different browsers, this object has different properties, but in general it is the same.

    XMLHttpRequest object methods

    Note that the method names are written in the same Camel-style as other Javascript functions. Be careful when using them.

    abort()- canceling 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")- initializing a request to the server, specifying the request method. Request type and URL are required parameters. The third argument is a boolean value. Usually true is always specified or not specified at all (the default is true). The fourth and fifth arguments are used for authentication (it is very unsafe to store authentication data in a script, since the script can be viewed by any user).

    send("contents")- send an HTTP request to the server and receive a response.

    setRequestHeader("header_name", "value")- set request header values.

    Properties of the XMLHttpRequest object

    onreadystatechange- one of the most important properties of the XMLHttpRequest object. Using this property, a handler is specified that is called whenever the status of an object changes.

    readyState- a number indicating the status of the object.

    responseText- representation of the server response as plain text (string).

    responseXML- a DOM-compatible document object received from the server.

    status- status of the response from the server.

    statusText- text representation of the response status from the server.

    You should take a closer look at the readyState property:

    • 0 - The object is not initialized.
    • 1 - The object is loading data.
    • 2 - The object has loaded its data.
    • 3 - The object is not fully loaded, but can be interacted with by the user.
    • 4 - The object is fully initialized; a response was received from the server.
    It is based on the readiness state of the object that you can provide the visitor with information about what stage the process of data exchange with the server is at and, possibly, notify him about this visually. Creating an XMLHttpRequest object

    As mentioned above, creating 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");

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

    Now, to achieve cross-browser compatibility, you need to combine all the functions into 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("Cannot create XMLHttpRequest"); ) return Request; )

    After all this, you can create this object and 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 point in time only one request to the server will be possible. You can create an object every time a request is made to the server (this will almost completely solve the problem).

    Request to the server

    The server request algorithm looks like this:

    • Checking the existence of XMLHttpRequest.
    • Initializing a connection to the server.
    • Sending a request to the server.
    • Processing of received data.
    To create a request to the server, we will create a small function that will combine in functionality the functions for GET and POST requests.

    /* Function for sending a request to a file on the server r_method - request type: GET or POST r_path - path to the file r_args - arguments like a=1&b=2&c=3... r_handler - function that handles the response from the server */ function SendRequest(r_method , r_path, r_args, r_handler) ( //Create a request var Request = CreateRequest(); //Check the existence of the request again if (!Request) ( return; ) //Assign a custom handler Request.onreadystatechange = function() ( // If the data exchange is completed if (Request.readyState == 4) ( //Pass control to the user handler r_handler(Request); ) ) //Check if it is necessary to make a GET request if (r_method.toLowerCase() == "get" && r_args.length > 0) r_path += "?" + r_args; //Initialize the connection Request.open(r_method, r_path, true); if (r_method.toLowerCase() == "post") ( //If this is POST- request //Set the header Request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); //Send the request Request.send(r_args); ) else ( //If this is a GET request //Send a null request Request.send(null); ) )

    Creating a request has become much easier. For example, let's write a function that will receive the contents of a file on the server and output it to a container.

    Function ReadFile(filename, container) ( //Create a handler function var Handler = function(Request) ( document.getElementById(container).innerHTML = Request.responseText; ) //Send the request SendRequest("GET",filename,"", Handler);

    This is how interaction with the server occurs.

    Processing the response

    In the previous example, we made a request function to the server. But it is essentially unsafe, since we do not process the state of the object and the state of the response from the server.

    Let's add to our code so that it can display a visual notification about the loading process.

    Request.onreadystatechange = function() ( //If the data exchange is completed if (Request.readyState == 4) ( //Pass control to the user handler r_handler(Request); ) else ( //Notify the user about the download) ) ...

    As you already know, the XMLHttpRequest object allows you to know the status of the response from the server. Let's take advantage of this opportunity.

    Request.onreadystatechange = function() ( //If data exchange is completed if (Request.readyState == 4) ( if (Request.status == 200) ( //Pass control to the user handler r_handler(Request); ) else ( // We notify the user about the error that occurred) ) else ( //Notify the user about the download ) ) ...

    Server response options

    You can receive several types of data from the server:

    • Plain text
    If you receive plain text, then you can immediately send it to the container, that is, to the output. When receiving data as XML, you must process the data using DOM functions, and present the result using HTML.

    JSON is Javascript object notation. With its help, you can represent an object as a string (here you can give an analogy with the serialization function). When you receive JSON data, you must execute it to get a full Javascript object and perform the necessary operations on it. Please be aware that such data transmission and execution are not secure. You have to keep track of what comes in for execution.

    Sample JSON code:
    ( "data": ( "misc": [ ( "name" : "JSON element one", "type" : "Subheading 1" ), ( "name" : "JSON element two", "type" : " Subtitle 2" ) ] ) )

    When receiving such a code, perform the following action:

    Var responsedata = eval("(" + Request.responseText + ")")

    After executing this code, the object will be available to you responsedata.

    Working with server-side programming languages

    This kind of work is no different from ordinary work. For examples, I'll take PHP as the server-side language. Nothing has changed on the client side, but the server side is now represented by a PHP file.

    By tradition, let's start with greetings to our wonderful world:

    Echo "Hello, World!";

    When accessing this file, the string Hello, World will be returned to the client. As you can imagine, this presents enormous opportunities for building applications. By passing arguments when calling the server using XMLHttpRequest, you can parameterize the output, thereby providing extensive functionality to the Web application.

    In addition to PHP, you can use any other server-side programming language.

    From the author: this series of articles is designed to introduce front-end designers and beginning developers to AJAX technology, the main front-end technology. In the first lesson, we will touch on the basics of AJAX, begin to learn various details of this technology, learn what it is, how it works and what its limitations are.

    Let's get started! Please note: this assumes that you already know basic front-end technologies such as HTML and CSS.

    What is AJAX?

    AJAX stands for Asynchronous JavaScript and XML. AJAX refers to more than one technology, and it is not new. It's actually a group of technologies (HTML, CSS, Javascript, XML, etc.) that are tied together to create modern web applications.

    WITH using AJAX the client (browser) communicates with the server and requests data from it. The received response is processed, and changes are made to the page without completely reloading it. Let's look at the AJAX acronym:

    "Asynchronous" means that when the client requests data from the server, the browser does not freeze until it receives a response. On the contrary, the user can navigate through the pages. Once the server has returned the response, background the response begins to be processed by the corresponding functions.

    "JavaScript" is a programming language that is used to create an AJAX request object, parse that response, and update the DOM of the page.

    The client uses XMLHttpRequest or XHR API to send a request to the server. An API (application program interface) is a set of methods that define the rules of communication between two interested parties. However, the data coming from an AJAX request can be in any format, not just XML.

    How AJAX works

    To understand the basic working principle, let's take a look at the picture below:

    The picture describes a standard AJAX script:

    The user wants to see more articles and he or she clicks on the desired button. This event triggers the AJAX call.

    The request is sent to the server. Various data can be sent with the request. The request can be sent to a static file (for example, example.php) stored on the server. You can also do dynamic scripts(functions.php), at each stage of which there will be communication with the database (or other system) to retrieve necessary information.

    The database sends back the requested articles to the server. And the server sends them to the browser.

    JavaScript parses the response and updates part of the DOM (page structure). In our example, only the sidebar will be updated. The rest of the page remains unchanged.

    With this in mind, you'll understand why AJAX is such an important technology on the modern Internet. Developing applications for AJAX control we can control large amounts of data downloaded from the server.

    Live example using AJAX

    AJAX is everywhere now. To convince you of this, we will briefly look at several popular sites that make full use of this technology.

    Let's look at the principles first Facebook work and Twitter. When you scroll down the page, AJAX loads new content. Also, if you like or dislike questions and answers on Stack Overflow, AJAX is triggered again. As soon as you type something into the search bar on Google or Youtube, multiple AJAX requests are triggered.

    Moreover, if we want, we can track these requests. For example, in the Chrome console, this can be done by right-clicking and activating the Log XMLHttpRequests function.

    How to create a request

    We already said above that the XMLHttpRequest API is used to create a request. In addition, jQuery, the most popular JS library, has various Ajax functions and methods. In a series of articles we will look at various examples in pure JS and JQuery to send requests to the server.

    Request management

    Data retrieved from the server can be stored in various formats. XML, JSON, JSONP, plain text and HTML.

    XML

    XML (Extensible Markup Language) is one of the most popular formats for exchanging data between applications. The format is similar to HTML and uses tags as structure. However, there are no ready-made tags in XML; we set them ourselves. Example structure below:

    Mike Mathew Australian English Spanish French Russian

    < person >

    < name >Mike< / name >

    < surname >Mathew< / surname >

    < nationality >Australian< / nationality >

    < languages >

    < language >English< / language >

    < language >Spanish< / language >

    < language >French< / language >

    < language >Russian< / language >

    < / languages >

    < / person >

    The network is full online editors, with which you can create XML documents. My favorite is: XMLGrid.net. In this editor our example looks like this:

    JSON

    JSON (JavaScript Object Notation) is another popular data exchange format. In JSON, the example above would look like this:

    ( "name" : "Mike", "surname" : "Mathew", "nationality" : "Australian", "languages" : ["English", "Spanish", "French", "Russian"] )

    "name" : "Mike" ,

    JSON Editor Online

    In the JSN editor our example will look like this:

    Limitations in AJAX requests

    Before you start using AJAX, you need to know about the limitations. We will consider only two problems.
    The first is an error in the Chrome console:

    The error appears when the request references a local file. In this example, we wanted to access data from local file(Demo.json), which is not stored on the server. To resolve this problem, you can install a local server and store files there. Second problem:

    The error appears when the data from the request is stored on a different domain from our page (the error is known as the domain restriction rule). In our example, the data is stored on local server, and the page is stored on the Codepen server. Fortunately, these errors can be resolved.

    One way is CORS from W3C. But this mechanism requires changes to the configuration of files on the server. For example, this page describes how to configure Apache server. Another way is JSONP (JSON with padding).

    Conclusion

    This review gave you an idea of ​​what AJAX is, where you may have already encountered it, and also what types exist potential problems. We also reviewed the most popular data exchange formats. In the next article we will look at a working example. See you!