Irrevocable success php. A simple example of using PHP and AJAX. “What does success in life mean to you???”

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 requests 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 an add-on that extends the XMLHttpRequest object, the object contains many properties and methods that allow you to obtain more complete information about the server 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 execution 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 as plain text, tags will be processed and executed once inserted into the document object model ( DOM).
    • "script" - evaluates the response as JavaScript and returns it as plain text. Disables caching by adding the _= parameter to the query string, even if the cache parameter 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.
    By default, the value is false , ignores the HTTP request header fields, and when set to true, the AJAX request is transferred to the successful status ( 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 by jQuery. It is recommended that jQuery generate the unique name itself, 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 the 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 (a 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 HTTP response code indicating that the client was able to communicate with the server, but the server could not find the data as requested.): $.ajax(( statusCode : ( 404: function ()( // execute function if HTTP response code 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 + ) ) );

AJAX is a group of technologies that is used in web development to create interactive applications. AJAX allows you to transfer data from the server without reloading the page. This way you can get very impressive results. And the jQuery library greatly simplifies the implementation of AJAX using built-in methods.

To implement the technology, use the $.ajax or jQuery.ajax method:

$.ajax(properties) or $.ajax(url [, properties])

The second parameter was added in version 1.5 of jQuery.

url - address of the requested page;

properties - request properties.

For a complete list of options, see the jQuery documentation.

In this tutorial we use several of the most commonly used parameters.

success (function) - this function is called after the request has completed successfully. The function receives from 1 to 3 parameters (depending on the version of the library used). But the first parameter always contains the data returned from the server.

data (object/string) - user data that is passed to the requested page.

dataType (string) - possible values: xml, json, script or html. Description of the type of data that is expected in the server response.

type (string) - request type. Possible values: GET or POST. Default: GET.

url (string) - URL for the request.

Example 1

Easy text transfer.

$.ajax(( url: "response.php?action=sample1", success: function(data) ( $(".results").html(data); ) ));

There is a .result div element for the response.

Waiting for an answer

The server simply returns the string:

Echo "Example 1 - transfer completed successfully";

Example 2

We pass user data to the PHP script.

$.ajax(( type: "POST", url: "response.php?action=sample2", data: "name=Andrew&nickname=Aramis", success: function(data)( $(".results").html( data);

The server returns a string with the transmitted data inserted into it:

Echo "Example 2 - transfer completed successfully. Parameters: name = " . $_POST["name"] . ", nickname= " . $_POST["nickname"];

Example 3

Passing and Executing JavaScript Code

$.ajax(( dataType: "script", url: "response.php?action=sample3", ))

The server executes the code:

Echo "$(".results").html("Example 3 - Executing JavaScript");";

Example 4

We use XML. The example can be used to work with external XML, for example, an RSS feed.

$.ajax(( dataType: "xml", url: "response.php?action=sample4", success: function(xmldata)( $(".results").html(""); $(xmldata).find ("item").each(function())( $(" ").html($(this).text()).appendTo(".results"); ) ));

The server should return XML code:

Header("Content-Type: application/xml; charset=UTF-8"); echo true); // if $data is not specified $response = array("success" => true, "data" => $data); // if $data is specified

Using wp_send_json_success($data, $status_code); $data (string/array/number/object/boolean) The data that will be added to the result in the data array element before being encoded into JSON.
Default: no$status_code (number) HTTP status code to set. What are the status codes? C WP 4.7.
Default: null Examples #1 Determining successful processing of an AJAX request

This jQuery code sends an AJAX request to the plugin file ajax/save_field.php:

JQuery(document).ready(function($)( $("#btn_save").click(function(e)( e.preventDefault(); $.post(pluginUrl + "ajax/save_field.php", $(" #my-form").serialize(), function(json)( if(json.success) alert(json.data.message); else alert("Error" + json.data); )); )); ) );

This is the code in the save_field.php file that processes the submitted request. Here's how to use wp_send_json_success() :