A lesson in which simple examples Let's look at how to work with AJAX technology, namely, how to use the XMLHttpRequest object (XHR for short) to create synchronous HTTP requests to the server and receive responses from it.

Let's begin our introduction to AJAX technology by looking at an example (for beginners) that will request information from the server through a synchronous request.

A synchronous request, as opposed to an asynchronous one, freezes the web page after it is sent and before receiving the response, i.e. makes it inaccessible to the user. Synchronous requests are used quite rarely on websites, but it is better for beginners to learn AJAX technology with them.

Before moving on to creating an example, let's look at the main steps involved in developing a fragment of a page that works in accordance with AJAX technology. In this case, all actions are mainly carried out in JavaScript code after the occurrence of any event on the page (the user clicked a button, etc.) and consist of the following stages:

  • Retrieving some information (data) from a page or form (if necessary)
  • Sending a request to the web server
  • Receiving a response from the web server
  • Display results on the page if the response was successful.
  • Basics of Creating Synchronous AJAX Requests Example 1: Making a Synchronous AJAX Request

    Let's look at an example of executing a synchronous AJAX request to the server using the XMLHttpRequest method. In this example, we will request the data located in the data.txt file on the server and display it on the page in the span element.

    The example will consist of files index.html , script.js and data.txt , which for simplicity can be located on the server in one directory.

    Let's start development by creating an HTML page to which we will connect the script.js file. This file, or rather its contents, will do all the main work. But before we move on to its development, let’s create div and span elements on the page. The div element will act as a button, which when clicked will execute an AJAX request. And the span element will act as a container that will contain the response coming from the server.

    In addition, we will add more CSS styles to the page to decorate it a little. As a result, we should have the following HTML code:

    JavaScript AJAX #myDiv ( height: 30px; width: 100px; background-color: lightgreen; )

    Response (AJAX):

    After that, open the data.txt file and enter the text “Hello, world!” into it. Let's save and close the file.

    Finally, let's move on to creating the script.js file. The contents of this file will perform all the basic actions, i.e. send an ajax request to the server, receive a response from the server and update the page content (place the response in the span element).

    Consider creating this file step by step:


    JavaScript AJAX

    Click on the light green block and receive a response from the server “Example, world!”

    Response (AJAX):

    // get the element that has id="myDiv" var myDiv = document.getElementById("myDiv"); // subscribe to the click event of this element myDiv.addEventListener("click", function() ( // create an XMLHttpRequest object var request = new XMLHttpRequest(); // configure the request: GET - method, data.txt - URL by to which the request will be sent, false - synchronous request request.open("GET","data.txt",false); // send data to the server using the send method request.send(); // if the response status is 200 (OK) ) then if (request.status==200) ( // display the server response in the element that has id="answer" document.getElementById("answer").innerHTML = request.responseText; ) ))

    Hello World!

    Example 2: Processing a synchronous AJAX request on the server using PHP

    An example that will use AJAX technology to send a request to the server containing a parameter and display the response on the page.

    In this example, the page will consist of 3 buttons. The first button will have text 1, the second button text 2 and the third button text 3. Clicking on any of the buttons will make a synchronous request to the server. We will use GET as the request transmission method. And the address to which we will send the request and ajax.php parameters. We will receive data sent by the client on the server using the HTTP GET variable ($_GET). After this, we will process the received data on the server and return a response (string) to the client.

    JavaScript AJAX span ( font-weight: bold; color: red; )

    Click on one of the buttons and receive a response from the server using AJAX technology.

    1 2 3

    Response (AJAX):

    // get all button elements on the page var buttons = document.getElementsByTagName("button"); // subscribe to the click event of all elements button for (var i=0; i

    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. for a long time, and AJAX is a synthesis of the indicated technologies. AJAX is most often associated with the term Web 2.0 and is touted as the latest Web application.

    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 and text messages indicating that data is being exchanged with the server. You should 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 with the transfer of several and small parameters, but to update information or add new information, you will need to use a POST request, since it allows you to transfer large amounts of data.

    As already mentioned, AJAX uses asynchronous data transfer. This means that while the data is being transferred, the user can perform other necessary actions. At this time, the user should be notified that some kind of data exchange is taking place, otherwise the user will think that something wrong has happened and may leave the site, or re-call the function that he thinks is “frozen.” Indication during 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 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 style (Camel-style) as the others 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.

    Let's 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 it visually. Creating an XMLHttpRequest object

    As mentioned above, creating this object for each type of browser is a unique process.

    For example, to create an object in Gecko-compatible browsers, Konqueror and Safari, you need to use the following expression:

    Var Request = new XMLHttpRequest();

    And for Internet Explorer the following is used:

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

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

    Now, to achieve cross-browser compatibility, you need to combine all the functions into one:

    Function CreateRequest() ( var Request = false; if (window.XMLHttpRequest) ( //Gecko-compatible browsers, Safari, Konqueror Request = new XMLHttpRequest(); ) else if (window.ActiveXObject) ( // Internet explorer try ( Request = new ActiveXObject("Microsoft.XMLHTTP"); ) catch (CatchException) ( Request = new ActiveXObject("Msxml2.XMLHTTP"); ) ) if (!Request) ( alert("Cannot create XMLHttpRequest"); ) return Request; )

    After all this, you can create this object and not worry about performance on popular browsers. But you can create an object in different places. If you create it globally, then at a certain point in time only one request to the server will be possible. You can create an object every time a request is made to the server (this will almost completely solve the problem).

    Request to the server

    The server request algorithm looks like this:

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

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

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

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

    This is how interaction with the server occurs.

    Processing the response

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

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

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

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

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

    Server response options

    You can receive several types of data from the server:

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

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

    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 server part is now represented by a PHP file.

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

    Echo "Hello, World!";

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

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

    Note: You will need to specify a complementary entry for this type in converters for this to work properly.
  • async (default: true)

    By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false . Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8 , the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() .

    beforeSend

    A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5 , the beforeSend option will be called regardless of the type of request.

    cache (default: true, false for dataType "script" and "jsonp")

    If set to false , it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_=(timestamp)" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

    complete

    A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success" , "notmodified" , "nocontent" , "error" , "timeout" , " abort" , or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

    contents

    An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5)

    contentType (default: "application/x-www-form-urlencoded; charset=UTF-8")

    When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() , then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded , multipart/form-data , or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

    This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

    url: "test.html" ,

    context: document.body

    )).done(function () (

    $(this).addClass("done" );

  • converters (default: ("* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML))

    An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5)

    crossDomain (default: false for same-domain requests, true for cross-domain requests)

    If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true . This allows, for example, server-side redirection to another domain. (version added: 1.5)

    Data to be sent to the server. It is converted to a query string, if not already a string. It"s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values ​​with same key based on the value of the traditional setting (described below).

    dataFilter

    A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the "dataType" parameter.

    dataType (default: Intelligent Guess (xml, json, script, or html))

    The type of data that you"re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object , in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

    • "xml" : Returns a XML document that can be processed via jQuery.
    • "html" : Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    • "script" : Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _= , to the URL unless the cache option is set to true . Note: This will turn POSTs into GETs for remote-domain requests.
    • "json" : Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests that have a callback placeholder, e.g. ?callback=? , are performed using JSONP unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or () instead. (See json.org for more information on proper JSON formatting.)
    • "jsonp" : Loads in a JSON block using JSONP . Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=" , to the URL unless the cache option is set to true .
    • "text" : A plain text string.
    • multiple, space-separated values: As of jQuery 1.5 , jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml" . Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
  • A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values ​​for the second argument (besides null) are "timeout" , "error" , "abort" , and "parsererror" . When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as " Not Found" or "Internal Server Error." (in HTTP/2 it may instead be an empty string) As of jQuery 1.5 , the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.

    global (default: true)

    Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.

    headers (default: ())

    An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values ​​in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5)

    ifModified (default: false)

    Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false , ignoring the header. In jQuery 1.4 this technique also checks the "etag" specified by the server to catch unmodified data.

    isLocal (default: depends on current location protocol)

    Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file , *-extension , and widget . If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1)

    Override the callback function name in a JSONP request. This value will be used instead of "callback" in the "callback=?" part of the query string in the url. So (jsonp:"onJSONPLoad") would result in "onJSONPLoad=?" passed to the server. As of jQuery 1.5 , setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, ( jsonp: false, jsonpCallback: "callbackName" ) . If you don"t trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons.

    jsonpCallback

    Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it"ll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

    method (default: "GET")

    mimeType

    password

    A password to be used with XMLHttpRequest in response to an HTTP access authentication request.

    processData (default: true)

    By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded" . If you want to send a DOMDocument, or other non-processed data, set this option to false .

    scriptAttrs

    Defines an object with additional attributes to be used in a "script" or "jsonp" request. The key represents the name of the attribute and the value is the attribute"s value. If this object is provided it will force the use of a script-tag transport. For example, this can be used to set nonce , integrity , or crossorigin attributes to satisfy Content Security Policy requirements (version added: 3.4.0)

    scriptCharset

    Only applies when the "script" transport is used. Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. Alternatively, the charset attribute can be specified in scriptAttrs instead, which will also ensure the use of the "script" transport.

    statusCode (default: ())

    An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

    404 : function () (

    alert("page not found" );

    If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.

    (version added: 1.5)
  • A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

    Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup() . The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be canceled by a timeout; the script will run even if it arrives after the timeout period.

    traditional

    type (default: "GET")

    An alias for method. You should use type if you"re using versions of jQuery prior to 1.9.0.

    url (default: The current page)

    A string containing the URL to which the request is sent.

    username

    A username to be used with XMLHttpRequest in response to an HTTP access authentication request.

    xhr (default: ActiveXObject when available (IE), the XMLHttpRequest otherwise)

    Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

    xhrFields

    An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

    url: a_cross_domain_url,

    withCredentials: true

    In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.

    (version added: 1.5.1)
  • The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.

    At its simplest, the $.ajax() function can be called with no arguments:

    Note: Default settings can be set globally by using the $.ajaxSetup() function.

    This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.

    The jqXHR Object

    The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser"s native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

    As of jQuery 1.5.1 , the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:

    url: "https://fiddle.jshell.net/favicon.png" ,

    beforeSend: function (xhr) (

    xhr.overrideMimeType("text/plain; charset=x-user-defined" );

    Done(function (data) (

    if (console && console.log) (

    console.log("Sample of data:" , data.slice(0 , 100 ));

    The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

    • jqXHR.done(function(data, textStatus, jqXHR) ());

      An alternative construct to the success callback option, refer to deferred.done() for implementation details.

    • jqXHR.fail(function(jqXHR, textStatus, errorThrown) ());

      An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

    • jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) ( )); (added in jQuery 1.6)

      An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

      In response to a successful request, the function"s arguments are the same as those of .done() : data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail() : the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

    • jqXHR.then(function(data, textStatus, jqXHR) (), function(jqXHR, textStatus, errorThrown) ());

      Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

    Deprecation Notice: The jqXHR.success() , jqXHR.error() , and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done() , jqXHR.fail() , and jqXHR.always() instead.

    // Assign handlers immediately after making the request,

    // and remember the jqXHR object for this request

    var jqxhr = $.ajax("example.php" )

    Done(function () (

    alert("success" );

    Fail(function() (

    alert("error" );

    Always(function() (

    alert("complete" );

    // Set another completion function for the request above

    jqxhr.always(function () (

    alert("second complete" );

    The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

    For backward compatibility with XMLHttpRequest , a jqXHR object will expose the following properties and methods:

    • readyState
    • responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
    • status
    • statusText (may be an empty string in HTTP/2)
    • abort([ statusText ])
    • getAllResponseHeaders() as a string
    • getResponseHeader(name)
    • overrideMimeType(mimeType)
    • setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
    • statusCode(callbacksByStatusCode)

    No onreadystatechange mechanism is provided, however, since done , fail , always , and statusCode cover all conceivable requirements.

    Callback Function Queues

    The beforeSend , error , dataFilter , success and complete options all accept callback functions that are invoked at the appropriate times.

    As of jQuery 1.5, the fail and done, and, as of jQuery 1.6, always callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods , which are implemented internally for these $.ajax() callback hooks.

    The callback hooks provided by $.ajax() are as follows:

  • beforeSend callback option is invoked; it receives the jqXHR object and the settings object as parameters.
  • error callback option is invoked, if the request fails. It receives the jqXHR , a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
  • dataFilter callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success .
  • success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
  • Promise callbacks — .done() , .fail() , .always() , and .then() — are invoked, in the order they are registered.
  • complete callback option fires, when the request finishes, whether in failure or success. It receives the jqXHR object, as well as a string containing the success or error code.
  • Data Types

    Different types of response to $.ajax() call are subject to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.

    The available data types are text, html, xml, json, jsonp, and script.

    If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

    Sending Data to the Server

    By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

    The data option can contain either a query string of the form key1=value1&key2=value2 , or an object of the form (key1: "value1", key2: "value2") . If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false . The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

    jQuery.ajax() - makes a request to the server without reloading the page. This is a low-level method with a lot of settings. It underlies the operation of all ajax, which is often easier to understand and use, but still provides limited functionality compared to this method.

    $.ajax() returns an XMLHttpRequest object. In most cases you will not need to work with this object directly, but it is still available in case you need to abort the request manually.

    The $.ajax() function is passed an object consisting of key/value pairs that are used to initialize and manage the request.

    An Ajax request has two uses:

    jQuery.ajax(url [, settings ])

    The only difference from the previous version of the method is that the url property here is part of the settings, and not a separate parameter.

    List of settings
  • accepts (default: depends on DataType)
    Type: object.
    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. For example, the following example specifies valid customtypes:

    $.ajax(( accepts: ( mycustomtype: "application/x-some-custom-type" ), converters: ( "text mycustomtype": function(result) ( return newresult; ) ), dataType: "mycustomtype" ));

    $. ajax ((

    accepts: (

    mycustomtype : "application/x-some-custom-type"

    converters: (

    "text mycustomtype" : function (result) (

    return newresult ;

    dataType: "mycustomtype"

    } ) ;

  • async (default: true)
    Type: boolean.
    By default, all requests are sent 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 send requests synchronously, set this option to false. Cross-domain and jsonp requests cannot be executed synchronously. Please note that synchronous requests may block the browser while the request is running.
  • beforeSend(jqXHR, settings)
    Type: function.
    Contains a function that will be called immediately before sending an ajax request to the server. This function can be useful for modifying the jqXHR object (in earlier versions of the library (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.
    beforeSend refers to ajax events. Therefore, if the function specified in it returns false, the ajax request will be canceled. Starting with jQuery-1.5, beforeSend is called regardless of the request type.
  • cache (default: true, false for dataType "script" and "jsonp")
    Type: boolean.
    if you want the browser not to cache the request being made, then set this parameter to false. Please note that if the parameter is set to false, the string “_=” will be added to the URL.
  • complete(jqXHR, textStatus)
    Type: function.
    A function that is executed every time an AJAX request completes (after success and error have completed). Two parameters are passed to the function: jqXHR (in earlier versions of the library (up to 1.5), XMLHttpRequest is used instead of jqXHR) and the request execution status (string value: "success", "notmodified", "error", "timeout", "abort", or "parsererror").
    Starting with jQuery-1.5, you can pass an array of functions to the complete parameter rather than just one function. All functions will be called in the order in which they are specified in this array.
  • contents
    Type: object.
    The parameter appeared in jQuery-1.5. It is specified by an object in the format (string:regular expression) and determines how jQuery will parse the response from the server, depending on its type.
  • contentType
    Type: boolean or string.
    When sending a request to the server, data is transmitted in the format specified in contentType. The default is ‘application/x-www-form-urlencoded; charset=UTF-8’, which is suitable in most cases. If you specify this parameter explicitly, it will be sent to the server (even if no data was sent there).
    With jQuery-1.6 you can pass false to not set the title.
  • context
    Type: object.
    The object that will become the context after the request is completed (the value passed to the this variable). For example, if you specify a DOM element as a context, then all ajax request handlers will also be executed in the context of this DOM element. In this example keyword this will contain document.body:

    $.ajax(( url: "test.html", context: document.body )).done(function() ( $(this).addClass("done"); ));

    $. ajax ((

    url: "test.html" ,

    context: document. body

    ) ) . done(function()(

    $(this). addClass("done");

    } ) ;

  • converters (default: ("*text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML))
    Type: object.
    The parameter appeared in jQuery-1.5 Determines which functions will be used to convert values ​​from one type to another.
  • crossDomain (default: false for same domain, true for cross domain requests)
    Type: boolean.
    This option was introduced in jQuery-1.5. If you want to perform a cross-domain request (for example, JSONP) on the same domain, set the crossDomain setting to true. This allows, for example, server redirection to another domain.
  • data
    Type: object, string or array.
    Data that will be transferred to the server. If the data is not a string, it is converted to a query string. For GET requests, data is attached to the URL. An object must consist of key/value pairs. If the value is an array, then jQuery orders the values ​​depending on the traditional setting. By default, for example, (foo:["bar1", "bar2"]) becomes &foo=bar1&foo=bar2 .
  • dataFilter(data, type)
    Type: function.
    A function that will pre-process data sent by the server, i.e. it should act as a filter and return the cleaned string. Two parameters are passed to this function: the mentioned data and the parameter value dataType. The function specified in dataFilter must return processed data.
  • dataType (default: detected automatically (xml, json, script, or html))
    Type: string.
    The data type in which the response is expected from the server. If it is not set, jQuery will try to determine it automatically using the MIME received from the server.
  • error
    Type: function
    A function that will be called if a request to the server fails. It is provided with three parameters: jqXHR (until 1.5 XMLHttpRequest is used), a string describing the error that occurred, as well as an exception object if this occurred. Possible values second argument: "timeout", "error", "notmodified" and "parsererror" (in unexpected cases, null may be returned). As of jQuery-1.5, this parameter can accept either a single function or an array of functions.
    The error event does not occur when dataType is equal to script or JSONP.
  • global (default: true)
    Type: boolean.
    Responsible for the operation of global ajax request events (for example, ajaxStart or ajaxStop). If you set this parameter to false , global events for of this request will not be called.
  • headers
    Type: object.
    The parameter appeared in jQuery-1.5. Here you can specify additional request headers. The values ​​for this setting will be entered before the beforeSend function is called, where final changes to the headers can be made.
  • ifModified
    Type: boolean.
    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 calling Last-Modified header. Starting with 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).
  • isLocal
    Type: boolean.
    This option was introduced in jQuery-1.5.1. 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 value of the isLocal parameter globally - using the $.ajaxSetup() function, and not in the settings of individual ajax requests.
  • jsonp
    Type: string or boolean.
    Defines the name of the parameter that is added to the JSONP request url (by default, “callback” is used). For example, the setting (jsonp:"onJSONPLoad") is converted to the url part of the string "onJSONPLoad=?" . Starting from version 1.5, specifying false in this parameter prevents adding an additional parameter to the url. In this case, you need to set the jsonpCallback setting value. For example: (jsonp:false, jsonpCallback:"callbackName") .
  • jsonpCallback
    Type: string or function.
    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 a preferable option that simplifies the library's work. 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 the specified function it will be available in the first parameter).
  • method (default: "GET")
    Type: string.
    The parameter appeared in jQuery-1.9.0 Allows you to specify the type of request to the server ("POST", "GET", "PUT")
  • mimeType
    Type: string.
    The parameter appeared in jQuery-1.5.1 In this field you can specify the data type in which the response from the server is expected instead of XHR
  • password
    Type: string.
    Password for authentication on the server, if required.
  • processData (default true)
    Type: boolean.
    By default, the data transferred to the server is converted from an object to a query string (url format: fName1=value1&fName2=value2&...) and sent as "application/x-www-form-urlencoded" . If you need to send a DOM document or other data that cannot be converted, set the processData option to false .
  • scriptCharset
    Type: string.
    Applies only to Ajax GET requests, the dataType can be either “jsonp” or “script”. If a server on a third-party domain uses an encoding that is different from yours, you must specify the encoding of the third-party server.
  • statusCode
    Type: object.
    The parameter appeared in jQuery-1.5.0 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"); ) ) ));

    $. ajax ((

    statusCode: (

    404 : function () (

    alert ("page not found" ) ;

    } ) ;


    If the request was successful, then as a parameter, the anonymous function will take the same parameters as the handler functions for successful request execution (specified in the success parameter), and in case of an error, the same parameters as those of the error functions.
  • success(data, textStatus, jqXHR)
    Type: function, array.
    A function that will be called if the request to the server completes successfully. Takes 3 arguments:
    • data sent by the server and pre-processed;
    • string with execution status (textStatus);
    • jqXHR object (in versions prior 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.
  • timeout
    Type: number.
    Waiting time for a response from the server in milliseconds. Overwrites the global setting of the same parameter in $.ajaxSetup(). If this time is exceeded, the request will be completed with an error and an error event will occur, 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, the 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.
  • traditional
    Type: boolean.
    Set this parameter to true to use traditional conversion (serialization) options.
  • type (default: "GET")
    Type: string.
    Similar to the method parameter. The parameter is used in jQuery earlier than 1.9.0
  • url (default: current page address)
    Type: string.
    Defines the address to which the request will be sent.
  • username
    Type: string.
    Username to authenticate to the server, if required.
  • xhr (default: ActiveXObject in IE, the XMLHttpRequest in other browsers)
    Type: function.
    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 your own version of this object.
  • xhrFields
    Type: object.
    The parameter appeared in jQuery-1.5.1 A set of pairs (name: value) 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 ) ));

    $. ajax ((

    url: a_cross_domain_url,

    xhrFields:(

    withCredentials : true

    } ) ;

  • As mentioned above, $.ajax() is the most basic method, and all subsequent methods are just wrappers. Very often there is no need to call this function, because There are higher level alternatives such as , and . They are easier to understand and use, although $.ajax() is a more flexible solution.

    The simplest use case would be to call $.ajax() without specifying parameters:

    $. ajax();

    Event Handlers

    The beforeSend, error, dataFilter, success and complete settings 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 if the request fails;
    • dataFilter occurs when data arrives from the server. Allows you to process “raw” data sent by the server;
    • success occurs if the request completes successfully;
    • complete occurs whenever the request completes.
    • success : function () (

      alert ("Data sent successfully." ) ;

      } ) ;

      Attention! The .success(), .error() and .complete() settings discussed above were added to jQuery-1.5 in addition to the standard .done(), .fail() and .then() methods for the deferred object, which can be used to set handlers , however starting with jQuery-1.8 these three methods will become deprecated.

      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.
      • “text” - the received data will be available in plain text, without preliminary processing.
      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 the 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

      url: "test.php" ,

      success : function (data ) (

      alert ("Data received: " + data ) ;

      } ) ;

    I suggest that at the very beginning of the article we remember that AJAX technology stands for Asynchronous JavaScript and XML. This is what it is main feature technologies. In the case of asynchronous data transfer, the browser does not reload the page and does not freeze while waiting for a response!

    It's easy to enable asynchronous transfer - just use the parameter (usually the third in order) of the open() method, where you should specify true. Accordingly, if you set it to false, the browser will hang while receiving a response from the server, be it a like, a rating, or something else. Imagine what happened before the creation of asynchronous data transfer? The server crashed - the page froze.

    Enable asynchronous data transfer. Open parameters (transfer method, file action, asynchronous or synchronous).

    JS code (Ajax)

    Xmlhttp.open("GET","ajax.php",true);
    Now the sent request will be processed independently of other scripts on the page, and will be processed only upon receipt. Received a response from the server after 20 seconds? Well, then we processed it, and don’t hang up.

    Asynchronous sending Set the parameter true to open(). What to do when the response is ready, write in the onreadystatechange event (for example, display in this object on the page):

    JS code (Ajax)

    Xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
    }
    xmlhttp.open("GET","ajax.php",true);
    xmlhttp.send();

    Synchronous transmission Attention! I describe synchronous transmission only out of decency. In our case (considering Ajax), it’s like driving a cart into the 21st century. However, to do this, we insert false into the open() method:

    Xmlhttp.open("GET","ajax.php",false);
    If you still want to use a similar model, then try to do it only for small requests. In the case of large requests, the browser freezes, and the user gets scared and leaves the page or closes the application - depending on where you are using it.

    JS code (Ajax)

    Xmlhttp.open("GET","ajax_info.txt",false);
    xmlhttp.send();
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    Thank you for your attention!

    Finally, let's move on to the next lesson with an example of Ajax and a TXT file!


    Close