A simple example of using PHP and AJAX. Ignoring data that remains unchanged. Setting basic parameters for Ajax requests

A set of key/value pairs that configure the request AJAX. All parameters are optional. It is acceptable, but not recommended, to set a default value for any parameter using the $.ajaxSetup() method.
The $.ajax() method supports the following parameters:

    accepts (default: depends on dataType ).

    Type: PlainObject.
    A set of key/value pairs that are sent to Accept request header. This header tells the server what kind of response the request will accept in response. Note that the value of the parameter specified in dataType (the type of data we expect from the server) is mapped to that specified in the parameter. In addition, to correctly process the response from the server, you must specify a function in the converters parameter that returns the converted response value. For example: $.ajax(( accepts : ( mycustomtype: "application/x-some-custom-type " ) , // specify how to process the response converters : ( "text mycustomtype ": function ( result) ( // return the converted response value return newresult; ) ) , // Expected data type ("mycustomtype") dataType : "mycustomtype" ) );

    async (default: true ).

    Type: Boolean.
    By default, all requests are sent asynchronously; if you need to organize synchronous requests, then set this parameter to false . Note that cross-domain queries and an element whose dataType parameter is "jsonp" do not support queries in synchronous mode. Please note that using synchronous requests you can temporarily block the browser by disabling any actions while the request is active.

    beforeSend. Type: Function (jqXHR jqXHR,PlainObject settings).
    A callback function that will be called before the AJAX request is made. The function allows you to change the jqXHR object (in jQuery 1.4.x the XMLHTTPRequest object) before it is sent. The jqXHR object is a add-on that extends the XMLHttpRequest object, the object contains many properties and methods that allow you to get more full information about the server's response, and the object also contains Promise methods. If the beforeSend function returns false , then the AJAX request will be canceled. Since version jQuery 1.5 the beforeSend function will be called regardless of the request type.

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

    Type: Boolean.
    If set to false this will cause requested pages not to be cached by the browser. Note that false will only work correctly with HEAD And GET requests.

    complete.

    Type: Function(jqXHR jqXHR,String textStatus).
    A function that is called when the request ends (the function is executed after AJAX events "success" or "error"). Two parameters are passed to the function: jqXHR(in jQuery 1.4.x object XMLHTTPRequest) and a line corresponding to the request status ( "success", "notmodified", "nocontent", "error", "timeout", "abortion", or "parsererror"). Since jQuery 1.5, the complete parameter can accept an array of functions that will be called one by one.

    contents.

    Type: PlainObject.
    An object consisting of string/regex pairs that determine how jQuery will process (parse) the response depending on the content type. Added in jQuery 1.5.

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

    Type: Boolean, or String.
    Defines the type of content that is specified in the request when sending data to the server. Since jQuery 1.6, it is possible to specify the value false , in which case jQuery does not pass the field in the header Content-Type at all.

    context.

    Type: PlainObject.
    When executing AJAX callback functions, their execution context is the window object. The context parameter allows you to configure the function execution context so that $(this ) will refer to a specific DOM element, or object. For example: $.ajax(( url : "test.html ", context : $(".myClass "), // new function execution context success : function ()( // if the request is successful, call the function $(this ).html ("Everything is ok"); // add text content to the element with the class.myClass ) ) );

    converters

    Default values:
    ( "* text ": window.String, // any type in text "text html": true, // text in html "text json": jQuery.parseJSON, // text in JSON "text xml": jQuery.parseXML // text in XML) Type: PlainObject.
    An object containing the data type to convert and how to convert it. The value of each converter is a function that returns the converted response value. Added in jQuery 1.5.

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

    Type: Boolean.
    If you want to make a cross-domain request while on the same domain (for example a jsonp request), then set this parameter to true . This will allow, for example, to redirect a request to another domain from your server. Added in jQuery 1.5.

    Type: PlainObject, or String, or Array.
    Data that will be sent to the server. If they are not a string, they are converted to a query string. For GET requests, the string will be added to the URL. In order to prevent automatic processing you can use the processData parameter with the value false . If data is transferred as part of an object, then it must consist of key/value pairs. If the value is an array, jQuery serializes multiple values ​​with the same key (depending on the value of the traditional parameter, which enables the traditional serialization type based on the $.param method).

    dataFilter.

    Type: Function(String data,String type) => Anything .
    The function is called after the successful completion of an AJAX request and allows you to process the “raw” data received from the server response. The return of data must occur immediately after processing. The function takes two arguments: data- data received from the server in the form of a string and type- the type of this data (the value of the dataType parameter).

    dataType (default: xml, json, script, or html).

    Type: String.
    Defines the type of data you expect to receive from the server. If the data type is not specified, then jQuery will try to determine it based on the MIME type from the response ( XML type MIME will result in XML, as of jQuery 1.4 json will give an object JavaScript, script will execute the script and everything else will be returned as a string).

    Basic types (the result is passed as the first argument to the success callback function):

    • "xml" - returns XML document that can be rendered using jQuery.
    • "html" - returns HTML like plain text, the tags will be processed and executed after being inserted into object model document ( DOM).
    • "script" - evaluates the response as JavaScript and returns it as plain text. Disables caching by adding a parameter to the query string _= , even if cache is true . This will turn the method POST V GET for cross-domain requests.
    • "json" - evaluates the response as JSON and returns an object JavaScript. Cross-domain "json" requests are converted to "jsonp", if jsonp is not specified in the request parameters: false. Data JSON are parsed in a strict order and must comply with the generally accepted format, any incorrect JSON is rejected and an error is thrown. As of jQuery 1.9, an empty response is not accepted; the server must return NULL or () as a response.
    • "jsonp" - loads data in the format JSON, using the download format JSONP. Adds an additional parameter "?callback=? " to the end URL addresses for specifying the name of the handler function. Disables caching by adding the _= parameter to URL address, even if the cache parameter is true .
    • "text" is a regular text string.
    • multiple values ​​- values ​​are separated by a space. Since version 1.5, jQuery can convert the data type that is received in the Content-Type of the header to the data type that you require. For example, if you want a text response to be interpreted as XML, use "text XML" for that data type. You can also make a JSONP request, receive it as text and interpret it as XML: "jsonp text XML" . The following line will do the same: "jsonp XML" , jQuery will try to convert from JSONP V XML, after an unsuccessful attempt will try to convert JSONP into the text, and then from the text into XML.
  • Type: Function(jqXHR jqXHR,String textStatus,String errorThrown).
    A callback function that is called if the AJAX request was not completed. The function receives three arguments:

    • jqXHR- jqXHR object (in jQuery 1.4.x, XMLHttpRequest object).
    • textStatus- a string describing the type of error that occurred. Possible values ​​(other than null ) are not "timeout", "error", "abortion" And "parsererror".
    • errorThrown- additional exception object if occurred. When an error occurs HTTP the argument receives the text part of the state, e.g. "Not Found", or "Internal Server Error".
    Since version jQuery 1.5 It is allowed to pass an array of functions as a parameter value, and each function will be called in its turn. Note that this handler is not called for cross-domain scripts and JSONP requests.
  • global (default: true ).

    Type: Boolean.
    A Boolean parameter that determines whether global AJAX event handlers are allowed to be called for this request. The default value is true . If you need to prevent global event handlers such as .ajaxStart() or .ajaxStop() from being called, then use false .

    headers (default: ( ) ).

    Type: PlainObject.
    An object that contains key/value pairs of additional request headers to be sent along with the request using the XMLHttpRequest object. Please note that the title X-Requested-With: XMLHttpRequest is always added, but the value of XMLHttpRequest can by default be changed using this parameter. Headers values ​​can also be overridden by the beforeSend parameter. Added in jQuery 1.5.

    ifModified (default: false ).

    Type: Boolean.
    Defaults to false , ignores header fields HTTP request, and if the value is true, the AJAX request is transferred to the status successfully ( success), only if the response from the server has changed since the last request. Validation is done by checking the Last-Modified header field. Since version jQuery 1.4, in addition to the Last-Modified header, the “etag” is also checked ( entity tag) is a private identifier assigned by a web server to a specific version of a resource found at a URL. If the resource content for this address changes to a new one, a new etag is assigned.

    isLocal (default: depends on current location).

    Type: Boolean.
    Use true to define the current environment as "local" (eg file:///url), even if jQuery doesn't recognize it as such by default. The following protocols are currently recognized as local: file, *-extension And widget. If you need to change the isLocal parameter, it is recommended to do this once using the $.ajaxSetup() function. Added in jQuery 1.5.1.

    Type: Boolean, or String.
    Overrides the callback function name in JSONP request. This value will be used instead of "callback" ( "http://domain.ru/test.php?callback=?") as part of the query string in the URL. For example, the value (jsonp: "onLoad") will be passed to the server as the following query string "http://domain/test.php?onLoad=?".
    Since jQuery 1.5, setting the jsonp parameter to false prevents the string "?callback" from being added to the URL, or attempts to use "=?" to resolve the response. In this case, you must additionally specify the value of the jsonpCallback parameter, for example: ( jsonp : false , jsonpCallback : "callbackName " ) For security reasons, if you do not trust the target of your AJAX requests, then it is recommended to set the value of the jsonp parameter to false .

    jsonpCallback.

    Type: String, or Function.
    Specifies the name of the callback function for JSONP request. This value will be used instead of a random name that is automatically generated and assigned jQuery library. It is recommended that jQuery generate its own unique name, this will make it easier to manage requests and handle possible errors. In some cases, setting your own function name will improve browser caching GET requests.
    Since jQuery 1.5, you can specify a function as the value of the jsonpCallback parameter. In this case, the value of the jsonpCallback parameter must be set to the return value of this function.

    method (default: "GET").

    Type: String.
    Method HTTP, used for the query (for example, "POST", "GET", "PUT"). Added in jQuery 1.9.0.

    mimeType.

    Type: String.
    A MIME type that overrides the default MIME type specified in the XHR object. Added in jQuery 1.5.1.

    password.

    Type: String.
    Password to be used with XMLHttpRequest in the response to the access authentication request HTTP.

    processData (default: true).

    Type: Boolean.
    By default, data passed to the data parameter as an object will be processed and converted to a query string suitable for the default data type "application/x-www-form-urlencoded". If you need to send DOMDocument , or other unprocessed data, then set this parameter to false .

    scriptCharset.

    Type: String.
    Sets the charset attribute (character encoding) to HTML tag, used in the request. Used when the encoding on the page differs from the encoding of the remote script. Please note that the scriptCharset parameter only applies to cross-domain requests with a type parameter with the value "GET"(default) and dataType parameter with value "jsonp", or "script".

    statusCode (default: ( ) ).

    Type: PlainObject.
    Numeric codes object HTTP and functions that will be called when the server response code has the appropriate value ( specific code HTTP). For example, the following function will be called if a response code is received from the server 404 , or "Not found" (standard code HTTP response indicating that the client was able to communicate with the server, but the server cannot find the data as requested.): $.ajax(( statusCode : ( 404: function ()( // execute the function if the HTTP response code is 404 alert( "page not found"); , 403: function ()( // execute the function if the HTTP response code is 403 alert("access denied "); ) ) ) );

    success.

    Type: Function (Anything data,String textStatus, jqXHR jqXHR).
    A callback function that is called if the AJAX request is successful. The function is passed three arguments:

    • data- data returned from the server. The data is formatted according to the parameters dataType , or dataFilter , if specified
    • textStatus- a string describing the status of the request.
    • jqXHR- jqXHR object (up to version jQuery 1.4.x XMLHttpRequest object).
    Since version jQuery 1.5 It is allowed to pass an array of functions as a parameter value, and each function will be called in its turn.
  • timeout.

    Type: Number.
    Installs in milliseconds request timeout. Meaning 0 means no timeout has been set. Please note that this parameter overrides the timeout value set using the $.ajaxSetup() function. The wait timeout starts at the moment the $.ajax() method is called.

    traditional.

    Type: Boolean.
    If you plan to use traditional serialization options (suitable for use in string URL request or request AJAX), then set the value of this parameter to true .

    type (default: "GET").

    Type: String.
    An alias for the method parameter. You should use type if you are using versions jQuery before 1.9.0.

    url (default: current page).

    Type: String.
    A line containing URL the address to which the request is sent.

    username.

    Type: String.
    The username that will be used with the XMLHttpRequest in the response to the access authentication request HTTP.

    xhr (default: ActiveXObject, when available ( Internet Explorer ), in other cases XMLHttpRequest .

    Type: Function() .
    Callback to create an XMLHttpRequest object. With this parameter, you can override the XMLHttpRequest object to provide your own implementation.

    xhrFields.

    Type: PlainObject.
    An object containing field_name:field_value pairs that will be set to the XHR object. For example, you can define whether cross-domain requests should be created using credentials such as cookie, authorization headers or TLS certificates: $.ajax(( url : "cross_domain_url ", // the address to which the request will be sent xhrFields : ( withCredentials: true // supported in jQuery 1.5.1 + ) ) );

In the era modern web, most websites are becoming more interactive. If previously, in order to receive updated data, we needed to refresh the entire page, now technologies have appeared that allow us not to load the entire page, but only a separate part of it. In turn, this provides convenience to both users and server owners, because the page will load faster for the user, since only a separate part of the page is loaded, and the server does not need to generate the page every time and give it to the user. These capabilities are easy to implement with php help and ajax.

Today we will look small example for a better understanding of how AJAX concept works. Sometimes it is difficult for beginners to understand how php and ajax interact with each other; many people are looking for examples of how to validate forms on the fly without reloading the entire page. I will briefly show you how this is done, so that you can understand the basics and principles that will allow you to more quickly master other tools and write your own scripts in the future.

Let's come up with a small task for ourselves, we will check the presence of an email address in the database without reloading the page using php and ajax. This example will demonstrate well how we can interact with the server without reloading the page in the browser, and also, this is often used for various types of user form validations. In the root directory we will create 3 files named index.php, email.php, validate.js.

Creating a page

Let's create a simple page with one form that contains only one field for entering an email.
Index.php file syntax

AJAX Tutorial

The easiest way to work with AJAX is to connect the jQuery framework, which is exactly what I did. jQuery provides us with an easy-to-understand and easy-to-use syntax for sending AJAX requests, so why not take advantage of it?

Creating a js script

Syntax of the validate.js file

$(document).ready(function())( var email = ""; $("#email").keyup(function())( var value = $(this).val(); $.ajax(( type: "POST", url:"email.php", data:"email="+value, success:function(msg)( if(msg == "valid")( $("#message").html("This Email can be used. This Email is already taken."); ) ) )); )); $("#submit").click(function())( if(email == "")( alert("Please, put data to all email"); )else( $.ajax(( type: "POST", url:"email.php", data:"add_email="+email, success:function(msg)( $("#message" ).html(msg); ) ));

Handler in php

This script will receive a POST request from the client, process it and return the result. AJAX reads the result and makes a decision based on it.
Email.php file syntax

$connection = mysqli_connect("localhost","email","email","email"); if(isset($_POST["email"]) && $_POST["email"] != "")( $email = $_POST["email"]; $email = mysqli_real_escape_string($connection,$email); if (!filter_var($email, FILTER_VALIDATE_EMAIL))( echo "invalid"; )else( $sql = "SELECT id FROM email WHERE email="$email""; $result = mysqli_query($connection,$sql); if( mysqli_num_rows($result) == 1)( echo "invalid"; )else( echo "valid"; ) ) ) if(isset($_POST["add_email"]) && $_POST["add_email"] != "" )( $email = mysqli_real_escape_string($connection,$_POST["add_email"]); $sql = "INSERT INTO email(email) VALUES("$email")"; if(mysqli_query($connection,$sql))( echo Success"; )else( echo "Error"; ) )

In our PHP script, the most common code that processes a post request and prints certain text on the page. As a result, AJAX sends the request php script, the script processes it and produces the result, AJAX reads the result and changes the page in real time.

AJAX sends a POST request to the script using this piece of code:

$.ajax(( type:"POST", url:"email.php", data:"email="+value, success:function(msg)( if(msg == "valid")( $("#message ").html("This Email can be used."); email = value; )else( $("#message").html("This Email is already taken."); ) ) ));

type - Request type, POST or GET. In our case POST;
url - the address of the script to which the request is sent;
data - data that is transmitted in the request;
success - what to do as a result of successful request execution. In our case, the function is called;

In the script itself, the presence of an email in the database is checked every time a character is entered into the email field. In the script, the section $("#email").keyup(function()()); is responsible for processing input. , which checks for a keypress in a field with id = "email" .
As you can see, the code is quite simple and does not require particularly great skills to understand, everything is tied to processing the events keyup() - a key press, click() - a mouse click on an element. This is followed by an AJAX request and response from the script. Thus, using php and ajax you can get almost limitless possibilities for creating interactive pages.
This code does not pretend to be high-quality, but if you develop it, add the correct validations at the client and server levels, and introduce css, then it can be used in your projects.
If you have any questions, don't hesitate to write comments.
Wish you Have a good day and see you soon :)

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 in synchronous mode.

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 an additional parameter from being added to the url. 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. Make a request if necessary 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 jQuery data transforms 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.

To execute a request to the server it takes certain time. 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 of the javascript file requested in the ajax request. 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

The simplest use case would be to call $.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 ) ; ) ) ) ;

Let's update the content of the desired html page:

$.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). We will specify the custom function handleResponse as a handler for successful completion of a request:

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.

Prefilters is convenient for handling custom settings (that is, 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 ; ) ) ) ;

It is convenient to process and existing settings. 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" ) ) ;

Heh, I've always wanted to write one of those "X is considered harmful" posts.

Before I begin, let me say this: I believe that jQuery has had an incredible impact on the advancement of the Web. It enabled developers to do things that were previously considered unthinkable. Forced browser manufacturers to implement many features natively (without jQuery, we probably would never have had document.querySelectorAll). jQuery is still needed for those who cannot rely on modern goodies and are forced to support relics like IE8 or worse.

However, as much as I sympathize with these poor guys, they are in the minority. Today there are already tons of developers who don't need to support older browsers with their tiny market share. And let's not forget those who are not professional developers: students and researchers, they not only don't care about all this cross-browser functionality, they often don't need anything at all except one single browser! You probably expect that in academic circles everyone is happy to use the newfangled goodies of the Open Web Platform? It’s not even close, jQuery is just everywhere there. Why? Because jQuery is all they know, they simply don’t have the energy or time to keep up with new web developments. They don't need a reason to use jQuery, it just has to be used. Despite this fact, and the ability to already do all these things natively, I still believe that this is not the main reason to avoid jQuery.

Yes, most likely, you don’t need it... I’m definitely not the first to point out that almost everything that jQuery can do, native JavaScript can do today. So I won't repeat myself and just give a few links: I also won't waste time talking about file size and how much faster native methods are. This has all been chewed over more than once. Today I want to point out something different... but that's still not a reason not to use it. To avoid extending the prototypes of native objects, jQuery uses its own wrappers over these objects. In the past, extending native objects was considered a huge disadvantage, not so much because of potential collisions with other extensions, but because of constant memory leaks in IE6. And so it went from then on, calling $("div") will return us not a link to an element or a list of nodes, but a certain jQuery object. This means that the jQuery object contains completely different methods than a regular reference to a house element or a list of nodes.

However, these links pop up all the time in real projects. No matter how much jQuery tries to abstract them away, you still have to constantly operate on them, even if just by wrapping these references in $(). For example, the callback context in the case of a jQuery .bind() method call will be a reference to the home element, not a jQuery collection. It's also worth noting that you often use libraries from different sources, some of them need jQuery and some don't. All this leads to the fact that the output is a hellish mixture of native house elements, lists of nodes and jQuery objects.

If the developer follows the naming convention of jQuery objects (adding $ before the variable name) and regular variables containing references to native elements, then this certainly mitigates the problem (although people tend to forget about any conventions, but let's assume we live in an ideal world). However, in most cases, developers have never heard of such conventions, and as a result, their code is extremely difficult for people unfamiliar with it to understand. Every attempt to edit such code entails a lot of errors in the style of “Oh, damn, this is not a jQuery object, I forgot to wrap it in $()” or “Damn, that’s not a house element, I forgot to take it through $(..)” . To avoid embarrassment, developers often end up wrapping everything in $(), just in case. Reading the code after, you can see that the same variable is wrapped in $() many times. For the same reason, it becomes very difficult to refactor this code so that it does not use jQuery. So we essentially have a hopeless situation.

Even if you strictly follow variable naming conventions, there are still often situations where you need to call a native method on a home element or run a function from code that doesn't rely on jQuery. And after some time, your code will already be filled from top to bottom with translations of objects from jQuery to native ones and vice versa.

Let's say, after some time, you decide to add a couple more features for similar program and in most cases you'll end up wrapping all new references to home elements and collections in $() again. After all, you cannot always know exactly in which case you will need this or that link. So again she hopeless situation, which also applies to all future code!

Take any random script with a jQuery dependency and try to rid it of this dependency. They fled. You will see that your main task is not to convert methods into native ones, but to generally understand what the hell is going on here.

A pragmatic path to pure JS Of course, many libraries today require jQuery and as I recently