Examples of using ajax. Receiving data from the server. Handling successful requests

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 update pages.

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 tutorial series, we'll look at the basics of building AJAX requests 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 completely new page HTML, which the browser then outputs, 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 viewing in this moment time. 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.

Making a GET request using $.get()

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

In its simplest form, you can call a method like this:

Where url is URL address resource from which a 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 you can also 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 sends 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 text file on the server called 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 button element"Get weather forecast" 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.

    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 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.” Indication during data exchange Web application 2.0 plays a very important role: visitors may 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 response is usually processed XML document on the client side and converting data 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 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) ) ...

    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 represents the broadest 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.

    Makes a request to the server without reloading the page. This is a low-level method that has big amount settings. It underlies the operation of all other ajax methods. Has two usage options:

    url — request address.
    settings - in this parameter you can specify settings for of this request. Specified using an object in the format (name:value, name:value...) . None of the settings are required. You can set default settings using the $.ajaxSetup() method.

    List of settings

    ↓ name :type (default value)

    When a request is made, the headers indicate the allowed content types expected from the server. The values ​​of these types will be taken from the accepts parameter.

    By default, all requests without a page reload occur asynchronously (that is, after sending a request to the server, the page does not stop working while waiting for a response). If you need to execute the request synchronously, then set the parameter to false . Cross-domain and "jsonp" requests cannot be executed synchronously.

    Please be aware that executing requests in synchronous mode may result in the page being blocked until the request is fully completed.

    This field contains a function that will be called immediately before sending an ajax request to the server. Such a function can be useful for modifying a jqXHR object (in earlier versions libraries (up to 1.5), XMLHttpRequest is used instead of jqXHR). For example, you can change/specify the necessary headers, etc. The jqXHR object will be passed to the function as the first argument. The second argument is the request settings.

    In this field you can specify additional request headers. These changes will be entered before beforeSend is called, where final header edits can be made.

    When this setting is set to true , the request will be executed with the status "successful" only if the response from the server differs from the previous response. jQuery checks this fact by looking at the Last-Modified header. Since jQuery-1.4, in addition to Last-Modified, "etag" is also checked (both of them are provided by the server and are necessary to notify the browser that the requested data from the server has not been changed from the previous request).

    Allows you to set the source status of a page to local (as if it were over the file protocol), even if jQuery recognized it otherwise. The library decides that the page is running locally in the case of the following protocols: file, *-extension, and widget.

    It is recommended to set the parameter value isLocal globally - using the $.ajaxSetup() function, and not in the settings of individual ajax requests.

    Defines the name of the parameter that is added to the url during a jsonp request (by default, “callback” is used - “http://siteName.ru?callback=...").

    As of jQuery-1.5, setting this parameter to false will prevent it from being added to the url additional parameter. In this case, you must explicitly set the value of the jsonpCallback property. For example: (jsonp:false, jsonpCallback:"callbackName") .

    Defines the name of the function that will be called when the server responds to a jsonp request. By default, jQuery generates a custom name for this function, which is more preferred option, simplifying the work of the library. One of the reasons to specify your own jsonp request processing function is to improve caching of GET requests.

    As of jQuery-1.5, you can specify a function in this parameter in order to handle the server response yourself. In this case, the specified function must return data received from the server (in specified function they will be available in the first parameter).

    By default, all data transmitted to the server is pre-converted into a string (url format: fName1=value1&fName2=value2&...) corresponding to "application/x-www-form-urlencoded". If you need to send data that cannot be subjected to such processing (for example, a DOM document), then you should disable the processData option.

    This parameter is used for cross-domain ajax requests of the GET type, the dataType can be either "jsonp" or "script". Defines the encoding in which the cross-domain request will be executed. This is necessary if a server on a foreign domain uses an encoding that is different from the encoding on the server of its native domain.

    (This setting was introduced in jQuery-1.5) a set of pairs in which request execution codes are associated with functions that will be called. For example, for code 404 (pages do not exist), you can display a message on the screen:

    $.ajax (( statusCode: ( 404 : function () ( alert ( "Page not found" ) ; ) ) ) ) ;

    Functions that respond to request success codes will receive the same arguments as the successful request handler functions (specified in the success parameter), and functions that respond to error codes will be the same as those of error functions.

    A function that will be called if the request to the server completes successfully. It will be passed three parameters: data sent by the server and already pre-processed (which is different for different dataTypes). The second parameter is a string with the execution status. The third parameter contains the jqXHR object (in earlier versions of the library (up to 1.5), XMLHttpRequest is used instead of jqXHR). As of jQuery-1.5, instead of a single function, this parameter can accept an array of functions.

    Waiting time for a response from the server. Set in milliseconds. If this time is exceeded, the request will be completed with an error and an error event will occur (see description above), which will have the status "timeout".

    Time is counted from the moment the $.ajax function is called. It may happen that several other requests will be running at this moment and the browser will delay executing the current request. In this case timeout may complete, although in fact, the request has not even been started yet.

    In jQuery-1.4 and earlier, when the XMLHttpRequest object times out, it will go into an error state and accessing its fields may throw an exception. In Firefox 3.0+, script and JSONP requests will not be aborted if they time out. They will be completed even after this time has expired.

    A function that will provide an XMLHttpRequest object. By default, for IE browsers this object is ActiveXObject, and in other cases it is XMLHttpRequest. With this option you can implement own version this object.

    (This setting was introduced in jQuery-1.5.1) A set of (name:value) pairs for changing/adding the values ​​of the corresponding fields of the XMLHttpRequest object. For example, you can set its withCredentials property to true when executing a cross-domain request:

    $.ajax (( url: a_cross_domain_url, xhrFields: ( withCredentials: true ) ) ) ;

    In jQuery-1.5, the withCredentials property is not supported by native XMLHttpRequest and will be ignored in a cross-domain request. In all next versions libraries, this has been fixed.

    Event Handlers

    The beforeSend, error, dataFilter, success and complete settings (their description is in the previous section) allow you to set event handlers that occur at certain points in the execution of each ajax request.

    beforeSend occurs immediately before the request is sent to the server. error occurs when the request fails. dataFilter occurs when data arrives from the server. Allows you to process “raw” data sent by the server. success occurs when the request completes successfully. complete occurs whenever a request completes.

    Example easy to use. We will display a message when the request is completed successfully:

    $.ajax (( url: "ajax/test.html" , success: function () ( alert ("Load was performed." ) ; ) ) ) ;

    Starting with jQuery-1.5, the $.ajax() method returns a jqXHR object that, among other things, implements the deferred interface, which allows you to specify additional execution handlers. In addition to the .done(), .fail() and .then() methods standard for the deferred object, with which you can install handlers, jqXHR implements .success(), .error() and .complete() . This is done to comply with the usual names of the methods by which handlers for executing ajax requests are installed. However, as of jQuery-1.8, these three methods will become deprecated.

    Some request types, such as jsonp or cross-domain GET requests, do not support the use of XMLHttpRequest objects. In this case, the XMLHttpRequest and textStatus passed to the handlers will contain the value undefined .

    Inside handlers, the this variable will contain the value of the parameter context. In case it was not set, this will contain the settings object.

    dataType parameter

    The $.ajax() function learns about the type of data sent by the server from the server itself (via MIME). In addition, there is an opportunity to personally indicate (clarify) how these data should be interpreted. This is done using the dataType parameter. Possible values ​​for this parameter:

    "xml"— the resulting xml document will be available in text form. You can work with him standard means jQuery (same as with an html document). "html"— the resulting html will be available in text form. If it contains scripts in tags, then they will be automatically executed only when the html text is placed in the DOM. "script"— the received data will be executed as javascript. Variables that typically contain the response from the server will contain a jqXHR object. "json", "jsonp"— the received data will be pre-converted into a javascript object. If parsing fails (which can happen if the json contains errors), then a file parse error exception will be thrown. If the server you are accessing is on a different domain, then jsonp should be used instead of json. You can learn about json and jsonp on Wikipedia. "text"— the received data will be available in plain text, without preliminary processing.

    Note 1: When a request is sent to a third-party domain (which is only possible with dataType equal to jsonp or script), error handlers and global events will not fire.

    Note 2: The data type specified in dataType must not conflict with the MIME information provided by the server. For example, xml data must be represented by the server as text/xml or application/xml . If this fails, jquery will try to convert the received data to the specified type (more on this in the Converters section).

    Sending data to the server

    By default, a request to the server is made using the HTTP GET method. If you need to make a request using the POST method, you need to specify the appropriate value in the type setting. Data sent using the POST method will be converted to UTF-8 if it is in a different encoding, as required by the W3C XMLHTTPRequest standard.

    The data parameter can be specified either as a string in the format key1=value1&key2=value2 (data transfer format in url), or as an object with a set of (name:value) pairs - (key1: "value1", key2: "value2") . In the latter case, before sending the data, jQuery converts given object to a string using $.param() . However, this conversion can be reversed by setting the processData setting to false . Conversion to a string is undesirable, for example, in the case of sending an xml object to the server. In this case, it is advisable to change the contentType setting from application/x-www-form-urlencoded to a more suitable mime type.

    Comment: Most browsers do not allow Ajax requests for resources with domains, subdomains, and protocols other than the current one. However, this limitation does not apply to jsonp and script requests.

    Receiving data from the server

    The data received from the server can be provided as a string or an object, depending on the value of the dataType parameter (see dataType above). This data is always available in the first parameter of the ajax request execution handler:

    $.ajax (( url: "some.php" , success: function (data) ( alert ( "Profit data: " + data ) ; ) ) ) ;

    For text and xml types, the data sent by the server will also be available in jqXHR, namely in its responseText or responseXML fields, respectively.

    Advanced Settings

    Using the global parameter, you can disable the execution of event handlers (.ajaxSend(), .ajaxError(), etc.) for individual requests. This can be useful, for example, if loading animation is started/stopped in these handlers. Then if some requests are executed very often and quickly, then it will be useful for them to disable the execution of handlers. For cross-domain script and jsonp requests, the global parameter is disabled automatically.

    If authentication data (login/password) is required to make a request to the server, then you can specify it in the username and password settings of the ajax request.

    A certain amount of time is allotted to complete a request to the server. If the server does not send a response during this time, the request ends with an error (status "timeout"). The waiting time for a response from the server can be changed by setting the required value (in milliseconds) in the timeout setting.

    It may happen that the host encoding is different from the encoding requested in the ajax request javascript file. In such cases, it is necessary to specify the encoding of the latter in the scriptCharset setting.

    In most cases, the Ajax request occurs asynchronously, but in some cases it may be necessary to execute the request sequentially (when further execution of the script is impossible without receiving a response from the server). You can make the request synchronous if you disable the async setting. However, it is worth remembering that in this case the page will freeze while waiting for a response from the server.

    Examples of using

    Most simple option use will be calling $.ajax() without specifying parameters:

    $.ajax();

    // a GET request will be sent to the server to the URL of the current page without specifying any parameters.

    If you need to load and execute a js file, you can do it like this:

    $.ajax (( type: "GET" , url: "test.js" , dataType: "script" ) ) ;

    Let's make a POST request to the server, specifying two parameters and notifying the user about the successfully completed request:

    $.ajax (( type: "POST" , url: "some.php" , data: "name=John&location=Boston" , success: function (msg) ( alert ( "Data arrived: " + msg ) ; ) ) ) ;

    $.ajax (( url: "test.html" , cache: false , success: function (html) ( $("#results" ) .append (html) ; ) ) ) ;

    Let's make a synchronous request to the server. While the request is being executed, the page will not respond to user actions:

    // write the data sent from the server to the html variable var html = $.ajax (( url: "some.php" , async: false ) ) .responseText ;

    As a parameter, we will send an xml object to the server. To transmit it correctly, you must cancel the preliminary conversion of parameters (processData:false). As a handler for successful completion of a request, we will specify custom function handleResponse:

    var xmlDocument = [ create xml document] ;

    $.ajax (( url: "page.php" , processData: false , data: xmlDocument, success: handleResponse ) ) ;

    Advanced Approach

    Starting with jQuery-1.5, there are three new directions that allow you to use $.ajax() even more deeply. The first of them (Prefilters) allows you to carry out additional manipulations immediately before sending the request. With the second approach (Converters), you can tell jQuery how to convert data received from the server if it does not match the expected format. The third approach (Transports) is the lowest level; it allows you to independently organize a request to the server.

    Prefilters

    This approach consists of setting up a handler that is called before each ajax request is made. This handler precedes the execution of any other ajax handlers. It is installed using the $.ajaxPrefilter() function:

    $.ajaxPrefilter (function (options, originalOptions, jqXHR) ( ) ) ;
    Where options
    — settings of the current request, originalOptions
    - default settings, jqXHR

    — jqXHR object of this request. It is convenient to process in Prefilters custom settings (i.e. new settings unknown to the library specified in the request). For example, you can enter own setup

    abortOnRetry , when enabled, unfinished requests will be reset if the following request is received at the same url:

    var currentRequests = ( ) ; $.ajaxPrefilter (function (options, originalOptions, jqXHR) ( if (options.abortOnRetry) ( if (currentRequests[ options.url ]) ( currentRequests[ options.url ] .abort () ; ) currentRequests[ options.url ] = jqXHR ; ) ) ) ;. For example, this is how you can change a cross-domain request to one redirected through your domain server:

    $.ajaxPrefilter (function (options) ( if (options.crossDomain) ( options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url ) ; options.crossDomain = false ; ) ) ;

    In addition, you can specify the dataType values ​​on which the prefilter will work. So, for example, you can specify json and script types:

    $.ajaxPrefilter ( "json script" , function (options, originalOptions, jqXHR) ( // Change options, check basic settings(originalOptions) and jqXHR object) ) ;

    Finally, you can change the dataType value to return the desired value:

    $.ajaxPrefilter (function (options) ( // change dataType to script if the url meets certain conditions if (isActuallyScript(options.url) ) ( return "script" ; ) ) ;

    This approach guarantees not only that the request will change its type to script, but also that other prefilter handlers specifying this type in the first parameter will also be executed.

    Converters

    This principle consists of installing a handler that will work if the dataType specified in the settings does not match the data type sent by the server.

    Converters is an ajax setting, so can be set globally:

    // this way you can set a handler that will work if, instead of // the type mydatatype you specified in dataType, data of type text is received $.ajaxSetup (( converters: ( "text mydatatype" : function ( textValue ) ( if (valid( textValue ) ) ( // processing the transmitted text return mydatatypeValue; ) else ( // if the data sent by the server does not correspond to what is expected, // you can throw an exception. throw exceptionObject; ) ) ) ) ;

    Converters will help you when introducing your own (custom) dataType. It is important to note that the name of such dataType should only use lower case! A request for the data type "mydatatype" mentioned above could look like this:

    $.ajax (url, (dataType: "mydatatype" ) ) ;

    A lesson in which we will look at creating simple asynchronous AJAX requests to the server using examples. We will use both the GET and POST methods as the request transmission method. On the server, we will process requests using PHP scripts.

    What is an asynchronous AJAX request?

    AJAX technology is mainly used to create asynchronous requests to the server. An asynchronous request is one that runs in the background and does not interfere with the user's interaction with the page.

    When sending an asynchronous request, the browser (page) does not “freeze”, i.e. you can work with it as before. But then how do you know when the response from the server arrives? To determine this, you need to monitor the browser's readyState property. This property contains a number whose value can be used to determine what stage the request is in. The following table shows the main values ​​of the readyState property and their corresponding states.

    Those. It turns out that we need to track when the value of the readyState property is equal to 4. This will mean that the sent request received a response from the server. The remaining values ​​are used quite rarely in practice, and some browsers may not support them.

    In order to determine what stage the request is at, you must use the XMLHttpRequest object's onreadystatechange event. This event occurs every time the value of the readyState property changes. Therefore, in the handler of this event (unnamed or named function), you can write actions that will check whether this property is equal to 4 and if it is equal, then, for example, display the server response on the page.

    Creating an asynchronous AJAX request (GET method)

    Let's look at creating an asynchronous AJAX request using an example, which will greet the user after loading the page and display his IP address.

    To do this, you need to create 2 files on the server in one directory:

  • welcome.html – HTML page that will be displayed to the user. On the same page we will place a script that will carry out all the necessary actions for AJAX to work on the client side.
  • processing.php – PHP file that will process the request on the server side and generate a response. Let's start development by creating the basic structure of the welcome.html file
  • Example of AJAX work Example of AJAX work // Here we will place the JavaScript code that will send a request to the server, receive it and update the contents of the page. All this will work without reloading the page

    Let's look at the sequence of actions that need to be performed on the client side (in JavaScript code):

    Let's prepare the data necessary to execute the request on the server. If no data is needed to complete the request on the server, then this stage you can skip it.

    Let's create a variable that will contain an instance of the XHR object (XMLHttpRequest).

    Let's configure the request using the open() method.

    The following parameters are specified:

    • The method by which the request will be sent to the server (GET, POST).
    • The URL that will process the request on the server.
    • Request type: synchronous (false) or asynchronous (true).
    • Username and password if required.
  • Let's subscribe to the onreadystatechange event of the XHR object and specify the handler as an anonymous or named function. After that, we will create code inside this function that will check the status of the response and execute certain actions On the page. The response that comes from the server is always in the responseText property.

    In addition to checking the value of the readyState property number 4, you can also check the value of the status property. This property determines the status of the request. If it is equal to 200, then everything is OK. Otherwise, an error occurred (for example, 404 - URL not found).

    Let's send a request to the server using the send() method.

    If we use the GET method to send a request, then pass the data to the parameter this method No need. They are sent as part of the URL.

    If we use the POST method to send a request, then the data must be passed as a parameter to the send() method. In addition, before calling this method, you must set the Content-Type header so that the server knows in what encoding the request came to it and can decrypt it.

    Contents of the script element:

    // 2. Creating the request variable var request = new XMLHttpRequest(); // 3. Setting up the request request.open("GET","processing.php",true); // 4. Subscribe to the onreadystatechange event and process it using the anonymous function request.addEventListener("readystatechange", function() ( // if the request states are 4 and the request status is 200 (OK) if ((request.readyState==4) && (request.status==200)) ( // for example, output an XHR object to the browser console console.log(request); // and the response (text) that came from the server to alert window console.log(request.responseText);

    // get an element with id = welcome var welcome = document.getElementById("welcome");

    Example of AJAX working Example of AJAX working window.addEventListener("load",function() ( var request = new XMLHttpRequest(); request.open("GET","processing.php",true); request.addEventListener("readystatechange" , function() ( if ((request.readyState==4) && (request.status==200)) ( var welcome = document.getElementById("welcome"); welcome.innerHTML = request.responseText; ) )); request.send();

    On the server (using php):

  • Let's get the data. If the data is sent via the GET method, then from the global array $_GET["name"] . And if the data is transferred using the POST method, then from the global array $_POST["name"] .
  • Using this data, we will perform some actions on the server. As a result, we get some answer. Let's display it using echo .