What is Ajax. AJAX: what it is, its impact on SEO, advantages and disadvantages of the technology. AJAX indexing by search engines

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

What is AJAX?

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 some time. 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.

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 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 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 passing several 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.” 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 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 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() - 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 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); ) )

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.

    This article describes AJAX at the feature and example level. The features of asynchronous interaction and examples of use are considered, but with a minimum of technical details.

    I hope it will be useful for understanding what AJAX is and what it is used for.

    What is AJAX? Example implementation.

    AJAX, or longer, A synchronous J avascript A nd X ml is a technology for interacting with the server without reloading pages.

    Due to this, response time is reduced and the web application is more reminiscent of a desktop in terms of interactivity.

    AJAX technology, as the first letter A in its name indicates, is asynchronous, i.e. the browser, having sent a request, can do anything, for example, display a message
    about waiting for a response, scrolling the page, etc.

    Here is the button code in the example above:

    When clicked, it calls the vote function, which sends a request to the server, waits for a response, and then displays a message about it in the div below the button:

    The server response will be here

    To exchange data with the server, a special XmlHttpRequest object is used, which can send a request and receive a response from the server. You can create such an object cross-browser, for example, like this:

    Function getXmlHttp())( var xmlhttp; try ( xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); ) catch (e) ( try ( xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); ) catch (E) ( xmlhttp = false; ) ) if (!xmlhttp && typeof XMLHttpRequest!="undefined") ( xmlhttp = new XMLHttpRequest(); ) return xmlhttp;

    You can read more about the details of implementing AJAX using XmlHttpRequest and other transports in the section on communicating with the server.

    We won’t dwell on this here and go straight to the vote function:

    // javascript voting code from the example function vote() ( // (1) create an object for a request to the server var req = getXmlHttp() // (2) // span next to the button // it will display the execution progress var statusElem = document.getElementById("vote_status") req.onreadystatechange = function() ( // onreadystatechange is activated when the server response is received if (req.readyState == 4) ( // if the request has finished executing statusElem.innerHTML = req.statusText / / show status ( Not Found, OK..) if(req.status == 200) ( // if the status is 200 (OK) - give a response to the user alert("Server response: "+req.responseText); ) // here you can add else with error handling request ) ) // (3) set the connection address req.open("GET", "/ajax_intro/vote.php", true);

    // the request object is prepared: the address is specified and the onreadystatechange function is created // to process the server response // (4) req.send(null); // send a request // (5) statusElem.innerHTML = "Waiting for server response..." )

  • The execution flow used by vote is quite typical and looks like this:
  • The function creates an XmlHttpRequest object
  • assigns the server response handler to onreadystatechange
  • opens the connection open
  • sends a request using the send call (the server response is received by the onreadystatechange function, which fires asynchronously)
  • The server handler to which the AJAX request is addressed (in the example this is vote.php) is essentially no different from regular page. The AJAX request sent by XmlHttpRequest is no different from a regular request.

    It's just that the text that the server returns is not shown as HTML, but is read and processed by the onreadystatechange function.

    The meaning of AJAX is to integrate technologies

    AJAX technology uses a combination of:

    • (X)HTML, CSS for presenting and styling information
    • DOM-model, operations on which are performed by javascript on the client side to provide dynamic display and interaction with information
    • XMLHttpRequest for asynchronous communication with a web server. In some AJAX frameworks and in some situations, an IFrame, SCRIPT tag, or other similar transport is used instead of XMLHttpRequest.
    • JSON is often used for data exchange, but any format will work, including rich HTML, text, XML, and even some EBML

    A typical AJAX application consists of at least two parts.

    The first one runs in the browser and is usually written in JavaScript, and the second one is on the server and is written, for example, in Ruby, Java or PHP.

    Data is exchanged between these two parts via XMLHttpRequest (or other transport).

    What can I do with AJAX?

    The point of AJAX is interactivity and fast response time.

    Small controls

    First of all, AJAX is useful for small elements associated with basic actions: add to cart, subscribe, etc.

    Dynamic loading of data from the server.

    For example, a tree whose nodes are loaded as they expand.

    At the time of its appearance, it was the only open postal service using AJAX for the following features.

    • Checking form input errors BEFORE submitting

      The username is sent to the server, and the result of the check is returned to the page.

    • "Instant" download

      The browser only contacts the server for data, rather than updating the entire cumbersome interface

    • Automatic "delivery" of letters to an open folder

      From time to time a request is sent to the server and if new letters arrive, they appear in the browser.

    • Autocompletion

      It is enough to enter the first letters of the recipient’s name, and the rest are completed automatically, as in desktop applications.

    Result: widespread popularity, high demand for accounts since opening.

    Synchronous model VS Asynchronous model

    In conventional programming, all operations are synchronous, that is, they are performed one after another.

    Relatively speaking, we act like this:

  • cast a fishing rod
  • waiting for it to bite
  • bit - turn on the spinning rod tightening
  • With the asynchronous approach we:

  • we hang a special bite detector on the fishing rod, ask it to pull the spinning rod when it bites
  • cast a fishing rod
  • we are doing other things
  • the bite detector is triggered, triggering the retraction of the spinning rod
  • That is, in the synchronous case, the fishing rod constantly attracts our attention. Catching fish is a sequential process.

    In the asynchronous version, we first set the program for what to do when biting, and then lowered the fishing rod to catch and went about other things.
    For example, we installed 5 more such fishing rods.

    Asynchronous programming is more difficult than synchronous programming, and at first it is unusual, because it in advance what will work is given after.
    That is, the program “what to do when it bites” must be set before the bite occurs, and it is generally unknown whether there are fish in the reservoir.

    There are techniques that make asynchronous programming easier, for example, the Deferred object (Twisted, Dojo, Mochikit), but this will be discussed in a separate article.

    Synchronous and asynchronous model in AJAX

    Let's return to our sheep: the browser, the server and, say, the database.

    In the synchronous model, the browser sends a request to the server and hangs, waiting for it to complete everything. necessary work. The server executes queries to the database, wraps the response in the required format and outputs it. Browser. Having received the answer, it calls the show function.

    All processes are performed sequentially, one after another.

    Network delays are included during the wait time, indicated in gray in the diagram.

    The user cannot do anything else on the same page while synchronous data is being exchanged.

    In the asynchronous model, the request is sent (“the bait is set”), and you can move on to something else. When the request is completed ("becked") - it is launched in advance
    a function prepared by the programmer (“pull up the spinning rod”) for displaying a server message.

    Here the server immediately notifies the browser that the request has been accepted for processing and releases it for processing. further work. When the response is ready, the server will forward it, and the corresponding display function will be called on the browser, but while this response is being generated and sent, the browser is free.

    The user can write comments, fill out and submit a form, etc.: New asynchronous requests can be made.

    The asynchronous model is characterized by an almost instantaneous response to user actions, so that the application feels convenient and fast.

    Because of this gap between the action and the actual result, the application becomes much more susceptible to errors.

    Especially in the case of multiple simultaneous asynchronous requests, you need to take care of the order of execution and response (race-conditions) and, in the event of an error, leave the application in a consistent state.

    Features of the asynchronous model
    • Difficult to implement
      • Insufficient browser capabilities (javascript)
      • The asynchronous model is more difficult to debug
    • Race conditions
      • Undefined execution sequence
      • You can do many simultaneous tasks ("fishing rods"), but the task started first may end last.
    • The reaction is immediate, but it is unknown what the result will be. Error handling is more complicated
      • Communication errors - disconnection, etc.
      • User errors - for example, there were not enough privileges
    • Integrity control (bugproof)
      • For example, the editor sent an asynchronous request to delete a tree branch. Adding to it must be disabled until the server response arrives. If suddenly there were not enough privileges, then the operation failed.
    • Interactivity
    • Fast interface

    There are only two advantages, but what advantages! The game is worth the candle.

    Asynchronous drag"n"drop.

    Sometimes for asynchronous operations it is necessary to do various “ear tricks”. For example, you want to do a drag"n"drop in a tree, that is, drag articles from one section to another with the mouse, and so that they change their parent on the server in the database.

    Drag "n" drop - this is "took the mice object - put it where it should be - done." But in the asynchronous model, everything cannot be “ready” right away.
    You need to check the privileges on the server, check whether the object still exists, in case another user deleted it.

    We need to somehow show that the process has started, but the result will be “what will happen...”. But as? In the asynchronous model, the mouse pointer cannot just hover over an object, turning into a watch.

    In this case, they either use synchronous requests to the server - and then everything really freezes, or the original solution is to put the object as if it had been transferred and inform with an animated icon that a response is awaiting.
    If the answer is negative, the response handler transfers the object back.

    Stale context, outdated context

    The example with drag"n"drop also touches on the problem of "stale context" - outdated context.

    Web is a multi-user environment. If used for navigation,
    Let's say a tree of articles, then many people work on it. One of them can delete a tree branch that the other is working on: conflict.

    As a rule, the following means are used to overcome such incidents:

    Editing Policy

    This is when everyone knows who is doing what and at the level of division of powers and personal communication such deletions are agreed upon. This option is obviously unsafe, but usually works.

    Locking and/or version control

    Locking - blocking edited documents.

    Version control - every new document becomes a version, so changes are never lost. Versioning entails conflicts when Petya started editing the document before Vasya, and saved it later. At the same time, in the latest version, Vasya’s changes were lost, although the penultimate (Vasya’s) version is definitely available in the system.

    You can read more about locking and versioning, for example, in the documentation for the Subversion version control system.

    Automatic context update

    The problem of outdated content can be 99% solved with instant auto-update.

    The browser maintains a constant connection with the server (or makes corrective requests from time to time) - and the necessary changes are sent through this channel.

    For example, new articles are sometimes loaded into an open branch of a tree; mail interface- new letters.

    In general, the problem of outdated context directly relates to the problem of data integrity. In any case, the server is responsible for the final integrity check, as with form validation.

    AJAX - What is it?

    When existing opportunities become scarce, and there is no room to improve what exists, then a technological breakthrough occurs. Such a breakthrough is AJAX (Asynchronous JavaScript and XML) - an approach to building user interfaces web applications, in which the web page itself loads without reloading needed by the user data. AJAX is one of the components of the DHTML concept.

    What does this technology give us? Currently WEB development applications tends to differentiate between the client and server parts, which is what determines the widespread use of templates such as Smarty and XSLT. Now projects are becoming more complex and intertwined various technologies becomes too expensive for a developer's time. So, for example, all formatting styles are put into CSS or XSL files, HTML or XML data are stored in other sections, server processors in third sections, databases in fourth sections. And if 5-6 years ago almost everywhere you could see the intertwining of all this in one file, now this is increasingly becoming a rarity.

    When developing more complex projects, there is a need for structured and readable code. You should not clutter the programmer's code with the layout designer's code, and the layout designer's code with the designer's edits, and so on.

    There is a need to differentiate work. So, for example, a designer will do his job, a layout designer will do his job, a programmer will do his work, and no one will interfere with each other. As a result, each project participant will only need to know the data with which he will have to work. In this case, the productivity of the group and the quality of the project increases significantly. Currently, this problem is successfully solved by using templates, but this also creates certain difficulties, since in order, say, to connect Smarty, you need to connect software module template processing, and clearly linked to the project structure. But this is not always possible and requires certain costs. It's a little easier to use XML + XSL as they provide more functionality, but it's an alternative, nothing more. What if we look towards something radically new that would allow us to combine everything better, using the capabilities of what we have? Try to imagine JavaScript, which has all the capabilities of PHP or Perl, including graphics and databases, which has much more convenient extensibility and practicality, and is also cross-platform.

    So what is AJAX? People first started talking about Ajax after the February 2005 article by Jesse James Garrett, “A New Approach to Web Applications.” Ajax is not a standalone technology. This is an idea that is based on two main principles.

    Using DHTML to dynamically change page content.

    Using XMLHttpRequest to contact the server on the fly.

    Using these two approaches allows you to create much more convenient WEB user interfaces on those website pages where active user interaction is required. Using Ajax became most popular after the company Google started actively use it when creating your sites, such as Gmail, Google maps and Google suggest. The creation of these sites confirmed the effectiveness of this approach.

    So in more detail: if we take the classic WEB application model:

    The client, typing the address of the resource he is interested in in the search bar, gets to the server and makes a request to it. The server performs calculations in accordance with the request, accesses the database, and so on, after which the received data goes to the client and, if necessary, is substituted into templates and processed by the browser. The result is the page that we see, and which 80% of the country's population located on the WEB call the Internet. This classic model, which has managed to prove itself and earn itself an honorable place in the sun. This is the most simple model interactions and, as a result, the most common. However, it is increasingly becoming insufficient. Imagine an on-line game "Battleship", which is played by two inveterate friends - a resident of South Africa and a resident of Japan. How can you use this model to make their game as enjoyable as possible? In any case, the data of sunk ships will be stored on the server, and in order to check whether the opponent has failed, it will be necessary to refresh the page every time and update outdated data. “But people invented caching,” you will say, and you will be absolutely right, but it won’t make it any easier. Caching will only speed up the time of interaction with the server, but will not eliminate the need to reload the page. Alternatively, you can put certain time self-updating, but in this case the page will be reloaded completely.

    Now let's look at the AJAX interaction model:

    The sequence of the client's actions is preserved and he most likely will not understand what will happen, and the word AJAX will be associated only with the name of the football club. But on the server side, everything looks different.

    When accessing the server, a page is generated that will be displayed to the user and prompt him to perform a sequence of actions that interests him. With a conscious (although not necessarily) choice of the client, his request will contact the AJAX module, which will perform all the calculations he is interested in and work with the server as such. But what's new? The main difference is that this method gives us the opportunity to dynamically access the server and perform actions that interest us. For example, we need to access the database and get the data we are interested in, which we will then use. We will store the data in an XML file that will be generated dynamically, thus:

    Create a new one JavaScript object:

    Var req = new ActiveXObject("Microsoft.XMLHTTP"); (for IE) var req = new XMLHttpRequest(); (For everything else)

    Then we write a function that uses this object

    Var req; function loadXMLDoc(url) ( // branch for native XMLHttpRequest object if (window.XMLHttpRequest) ( req = new XMLHttpRequest(); req.onreadystatechange = processReqChange; req.open("GET", url, true); req.send( null); // branch for IE/Windows ActiveX version ) else if (window.ActiveXObject) ( req = new ActiveXObject("Microsoft.XMLHTTP"); if (req) ( req.onreadystatechange = processReqChange; req.open("GET ", url, true); req.send(); ) ) )

    Tele HTML file we write a script that will:

    Function checkName(input, response) ( if (response != "")( // Response mode message = document.getElementById("nameCheckFailed"); if (response == "1")( message.className = "error"; )else( message.className = "hidden"; ) )else( // Input mode url = "http://localhost/xml/checkUserName.php?q=" \\ + input; loadXMLDoc(url); ) )

    In the file localhost/xml/checkUserName.php we process the data received from command line V in this case in the variable q. And we save the result in XML structure, which we store in the same file. This way we can receive and process data obtained from the database, or anything else we need. In addition, the server will only process the data that we need to update, and not the entire page if it is reloaded.

    Now let's return to two friends - lovers of sea battles: in view of the appearance of this innovation, we can do the following: check the XML file for every three seconds this check involves checking the database for new entry, that is, the move made by the opponent. If a move has been made, the page sinks ships without rebooting, thereby spoiling the mood of the participants in water battles. This functionality is achieved with the basic use of Javascript and style sheets. This example is quite clear, but far from complete; the application of this technology is much more significant.

    However, not all so simple. Let's now look at the negative traits.

    Firstly, we can only transfer data using the GET method, so large amounts of data will have to be left alone. This problem I've climbed the mountain more than once different sources, but gentlemen, there are Cookies, which are quite acceptable in cases of transferring more data than a GET request can accommodate, and Javascript, in turn, has functions for working with them.

    The second problem is cross-browser compatibility. The XMLHttpRequest object is not yet part of any standard (although something similar has already been proposed in the W3C DOM Level 3 Load and Save specification). Therefore, there are two different methods for calling this object in script code. In Internet Explorer, the ActiveX object is called like this:

    Var req = new ActiveXObject("Microsoft.XMLHTTP");

    In Mozilla and Safari this is easier (since there it is an object built into JavaScript):

    Var req = new XMLHttpRequest();

    All modern browsers support this object and problems will arise only for 1.8% of users (according to statistics from SpyLog) who use very old versions of browsers that do not support this object.

    And finally, security. Let's take a closer look at this. The main problem is that all data and source code of JavaScript functions can be seen by viewing source code pages, accordingly, an attacker can trace the logic of request execution and, under a certain set of circumstances, execute the set of commands he needs. This does not play a special role when we have a simple data comparison, but what to do in more complex situations, for example during authorization, and how to transfer passwords in this case. As mentioned above, Cookies come to the rescue. The necessary data can be sent using them, and they can also be processed. Let's take an example in which the user will be authenticated using the technology that the article is devoted to.

    When generating a page, we generate unique values, which we then place in server variables. And in Browser cookies, then during authorization we receive the username and password, which we need to pass to the processing module on the server.

    After the user has entered the data and pressed the Submit button, his password is entered into Cookies, and the user name is transmitted openly - with a link for example http://www.mubestajax.com/ajax.php?login=pupkin when receiving the data, the server first of all conducts reconciliation of the received data. Since the values ​​that we generated from the start of the server and then passed them to the global server variables and cookies must match, when checking the integrity of the transferred data, in case of a mismatch, the program stops working. If everything went well, then all the necessary data is extracted and the necessary calculations and work are carried out. This method of protection is quite simple and effective. But for big projects it won't fit.

    When security comes to the fore, it is better to use more complex and reliable solutions. But in most cases, these precautions will be more than enough, since the use of more complex modules entails the use of technologies that are not always included in standard software modern servers, the main feature of which is simplicity. This is why technologies such as MySQL and PHP have become very widespread, because... they provide ease of operation with their low resource consumption and sufficient reliability. And within the framework of this software, the solution proposed above is the best fit.

    In conclusion, I would like to say that AJAX, on the one hand, is a huge leap in WEB engineering, but on the other hand, it is a long-overdue stage of evolution that has opened new horizons in the field of software development. At the same time, this technology is still quite “raw” since its use at the moment is rather a pleasant exception. But I am sure that everyone will hear about it more than once.

    Most modern websites use a technology called AJAX to quickly and efficiently effective interaction with a visitor. AJAX has become a very popular method for retrieving data from a server in background and dynamic page updating.

    Developing JavaScript code to implement AJAX from scratch is a very time-consuming and tedious process. However, many JavaScript libraries, including jQuery, have an excellent high-level implementation of AJAX in the form of a set of methods and functions that make building websites easier and faster.

    In this series of lessons we will look at the basics of building AJAX requests with using jQuery. The following topics will be covered:

    • What is AJAX technology? How does it work? What are its advantages?
    • How to do it Various types AJAX requests using jQuery?
    • Sending data to the server using AJAX requests.
    • Processing and extracting data from AJAX responses from the server.
    • How to customize AJAX processing in jQuery and change default settings?

    Note: The tutorials focus on the client side portion of JavaScript. But developing the server side is also quite simple. For more complete information You should study materials on server-side programming languages, such as PHP.

    What is AJAX and how is it useful?

    AJAX is a web application development technique in which JavaScript code running in the visitor's browser communicates with the web server asynchronously, that is, in the background. The differences from regular web applications are as follows:

    • A typical web page contains links or forms that, when clicked or submitted, create a request to a new URL on the web server. The server sends a completely new HTML page, which the browser then renders, replacing original page. This approach takes a lot of time and is bad for the visitor, as he has to wait for the new page to load.
    • When using AJAX technology, JavaScript code makes a request to a URL on the server. The code can also send data along with the request. The JavaScript code then processes the server's response and acts accordingly. For example, calculations can be made with the returned data, a widget can be added or updated on the page, or a message can be sent to the visitor about updating the database on the server.

    Because the AJAX request runs in the background, the JavaScript code (and the visitor) can continue to interact with the page while the request is processed. The process is hidden from the visitor, who does not need to leave the page he is currently viewing. This approach makes AJAX pages very pleasant to work with.

    The fundamental point of AJAX is the JavaScript XMLHttpRequest object. It provides a number of methods such as open() , send() and onreadystatechange() which can be used when sending AJAX requests to the server and processing the responses in the background.

    Developing cross-browser JavaScript AJAX code can be quite a tedious process. Luckily, jQuery gives you several easy-to-use AJAX methods that allow you to abstract away a lot of low-level operations.

    For those who are more curious, the word AJAX is an abbreviation of the first letters of the expression in English language"A synchronous J avaScript A nd X ML" ( Asynchronous JavaScript and XML). However, the term can be misleading - the request does not have to be asynchronous and it does not have to use XML to send the data.

    Let's do GET request using $.get()

    The jQuery $.get() method provides an easy and convenient way make a simple AJAX request. It executes the request using HTTP method GET (used to retrieve URLs, such as pages and images), instead of the POST method (which is traditionally used to submit form data).

    IN simplest form you can call the method like this:

    Where url is the URL of the resource from which the response is expected. Typically this is a server-side script that performs some actions and can return some data:

    $.get("http://example.com/getForecast.php");

    Although it is also possible to request a static document:

    $.get("http://example.com/mypage.html");

    When requesting a URL, you can send data with the request. You can pass data in the query string, just like with a normal GET request:

    $.get("http://example.com/getForecast.php?city=rome&date=20120318");

    The correct way to do the same is to pass the data object as the second parameter to the $.get() method. The data object must contain information in the form of property name/property value pairs. For example:

    Var data = (city: "rome", date: "20120318" ); $.get("http://example.com/getForecast.php", data);

    Alternatively, you can pass the data to the $.get() method as a string:

    Var data = "city=rome&date=20120318"; $.get("http://example.com/getForecast.php", data);

    Receiving data from the server

    So far, we've looked at examples of using $.get() only to send requests to the server, ignoring any response that the server-side script might generate. But in most cases, your JavaScript code will wait for a response from a server-side script and process the received data.

    An AJAX request is asynchronous, which means it runs in the background while the rest of the JavaScript code continues to run. How, then, to receive a response from the server when the request is completed?

    You need to write a callback function that will be automatically executed when the AJAX request completes and the server sends a response. At a minimum, your function should accept the data returned by the server as its first argument:

    Function myCallback(returnedData) ( // We process the data returnedData )

    Once the callback function is created, you can pass it as the third argument to the $.get() method:

    Var data = (city: "rome", date: "20120318" ); $.get("http://example.com/getForecast.php", data, myCallback);

    Determining the response data type

    Typically, the server side transmits data in one of several common formats, including XML, JSON, JavaScript, or HTML. By default, jQuery tries to determine the most appropriate format and parse the data accordingly. But it is better to explicitly define the format.

    To specify the format, you need to pass the fourth argument to the $.get() method. This argument can be a string from the following list:

    • "xml"
    • "json"
    • "script"
    • "html"

    For example, if you know that the server script returns data in JSON format, then you call the $.get() method like this:

    $.get("http://example.com/getForecast.php", data, myCallback, "json");

    Example of using the $.get() method

    Here's an example of creating an AJAX request using the $.get() method and simple processing answer. For the example to work, you need to create a simple one on the server text file named getForecast.txt containing next text:

    ( "city": "Vasyuki", "date": "March 18, 2012", "forecast": "Blasting cold and slush", "maxTemp": +1 )

    This file will simulate a response in JSON format that could be generated by a weather forecast script on the server.

    Then we create the showForecast.html page in the same folder as getForecast.txt:

    Weather forecast $(function() ( $("#getForecast").click(function() ( var data = ( city: "Vasyuki", date: "20120318" ); $.get("getForecast.txt", data , success, "json"); )); function success(forecastData) ( var forecast = forecastData.city + " forecast on " + forecastData.date; forecast += ": " + forecastData.forecast + ". Maximum temperature: " + forecastData.maxTemp + "C"; alert(forecast); ) )); Get weather forecast

    Open showForecast.html in the browser and click the "Get weather forecast" button. In the message window we will receive the weather forecast from our server.

    Here's how the code works:

  • showForecast.html contains a "Get Weather Forecast" button element with ID getForecast .
  • The JavaScript at the top of the page is executed as soon as the page is loaded and the DOM is in a ready state.
  • The JavaScript code first binds a click event handler to the #getForecast button. This handler performs an AJAX GET request to getForecast.txt, passing the name of the city and date for the forecast. A success() callback function is also defined, which will be executed when the request completes. The format of the data returned by the server is defined as JSON.
  • The getForecast.txt file returns forecast data to the browser in JSON format.
  • The success() function is called. jQuery parses the JSON data received from getForecast.txt, converts it into a JavaScript object, and passes it to the function.
  • The function returns a forecastData data object and displays a message that contains several properties of the object, including the city name, forecast, and temperature.
  • A simple, few-line example demonstrates how an AJAX request works using the $.get() method.

    From the author: this series The articles are designed to introduce front-end designers and novice 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.

    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, the response begins to be processed in the background by the appropriate 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 execute dynamic scripts (functions.php), at each stage of which communication will occur with the database (or other system) to retrieve the 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 will understand why AJAX is such an important technology in modern internet. By developing applications running AJAX, 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.

    First, let's look at how Facebook and Twitter work. 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 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 for sending requests to the server.

    Request management

    Data pulled 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 an Apache server. Another way is JSONP (JSON with padding).

    Conclusion

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