Computer lessons

Receiving ajax data. A simple example of using PHP and AJAX

We've covered the basic mechanics of the jQuery $.ajax() method. Now it would be a good idea to consider cases from real practice: how and from where you can obtain data for transmission with an Ajax request.

Receiving data from the form.

There are several ways to get data from form fields:

  • Select each field separately, getting its value. However, this is not very convenient when there are many fields.
  • Use serialize() method
  • Use serializeArray() method
  • Let's dwell on the last two and not so much on how to obtain data ( everything is simple here), but on how to process them on the server side. Take, for example, this form:

    HTML ( index.html file)

    FULL NAME:
    Email:
    Gender: Male Female
    To receive letters:
    Yes
    No

    And let's write this JS code

    jQuery( script.js file)

    $(function())( $("#my_form").on("submit", function(e)( e.preventDefault(); var $that = $(this), fData = $that.serialize(); / / serialize the data // OR // fData = $that.serializeArray(); $.ajax(( url: $that.attr("action"), // take the path to the handler from the action type attribute: $that.attr( "method"), // transfer method - taken from the method attribute data: (form_data: fData), dataType: "json", success: function(json)( // If the request is completed successfully... if(json)( $that.replaceWith(json); // replace the form with the data received in the response. ) ) )); )); ));

    Now let's write a handler in such a way as to clearly see the difference between the serialize() and serializeArray() methods

    PHP handler ( file handler.php)

    $(name):

    I will not describe this example in detail here, because... we looked at it in detail in the previous article (only using the post() method). I’ll just note that here, in addition to type, we used several more parameters. To specify the target of the POST request, the url parameter described earlier is used. The data to be sent is specified using the data parameter, the value of which is set using the serialize() method described in the previous article. The type of data received from the server is specified in the dataType parameter.

    Working with Ajax Events

    Several parameters allow you to specify functions to handle events that can be fired throughout the lifecycle of an Ajax request. This is how you will specify the callback functions that play such an important role in Ajax requests. You have already become familiar with one of them when considering the success parameter in the previous example. The list of parameters associated with events, along with their brief descriptions, is shown in the table below:

    Handling successful requests

    In the examples above, when using the success parameter, two arguments were omitted from the function call - a message describing the result of the request and a jqXHR object. An example of using a function that takes these arguments is below:

    $(function() ( $.ajax(( url: "mydata.json", success: function(data, status, jqxhr) ( console.log("Status: " + status); console.log("jqXHR status: " + jqxhr.status + " " + jqxhr.statusText); console.log(jqxhr.getAllResponseHeaders()); var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ) )); ));

    The status argument is a string describing the outcome of the request. The callback function we specify using the success parameter is executed only for successful requests, so the value of this argument is usually success. The exception is when you use the ifModified parameter, described next.

    The callback functions for all Ajax events follow the same pattern, but this argument is most useful for a number of other events.

    The last argument is the jqXHR object. You don't have to figure out the status of the request before you start working with this object because you know that the function is executed only when the request succeeds. This example uses the jqXHR object to obtain information about the state of the request and the headers that the server included in the response, and to print this information to the console.

    In this case, the result looks like this (depending on which server you are using, you may have a different set of headers):

    Error processing

    The error parameter is used to specify a function that should be called when the request fails. A corresponding example is given below:

    Error (color: red; border: medium solid red; padding: 4px; margin: auto; width: 200px; text-align: center)

    $(function() ( $.ajax(( url: "NoSuchFile.json", success: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)) .appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ), error: function(jqxhr, status, errorMsg) ( $("") .text( "Status: " + status + " Error: " + errorMsg) .insertAfter("h1"); ) )); ));

    Here, the NoSuchFile.json file is requested, which is not present on the server, and therefore the request obviously cannot be completed, as a result of which the function specified using the error parameter will be called. The arguments to this function are the jqXHR object, the error status message, and the error message received in the server response. Inside this function, a div element is added to the document that displays the values ​​of the status and errorMsg arguments, as shown in the figure:

    Configuring request parameters before sending them

    The beforeSend parameter allows you to specify a function that will be called before requests are sent. This allows you to configure the request at the last minute by adding or replacing parameters passed to the ajax() method (which can be especially useful if multiple requests are using the same object containing the required parameter values). An example of using this approach is presented below:

    $(function() ( $.ajax(( success: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo("#row1") ; template.tmpl(data.slice(3)).appendTo("#row2"); ), error: function(jqxhr, status, errorMsg) ( $("") .text("Status: " + status + " Error: " + errorMsg) .insertAfter("h1"); ), beforeSend: function(jqxhr, settings) ( settings.url = "mydata.json"; ) )); ));

    The arguments to this function are a jqXHR object (which can be useful for customizing request headers or canceling the request before it is sent) and an object containing the parameters passed to the ajax() method. In this example, the URL for the Ajax request is set using the beforeSend parameter.

    Setting Multiple Event Handlers

    In the previous examples, we responded to the occurrence of events associated with Ajax requests by calling a single function, but in the success, error, complete and beforeSend parameters you can specify an array of functions, each of which will be executed when the corresponding event is triggered. A simple example of this is given below:

    $(function() ( $.ajax(( success: , beforeSend: function(jqxhr, settings) ( settings.url = "mydata.json"; ) )); function processData(data, status, jqxhr) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ) function reportStatus(data, status, jqxhr) ( console.log("Status: " + status + " Result code: " + jqxhr.status); ) ));

    In this example, the success parameter is set to an array consisting of two functions, one of which uses data to add elements to the document, and the second of which prints information to the console.

    Setting up context for events

    The context parameter allows you to specify the element that will be assigned to the this variable when the event handler is called. This can be used to access target elements in a document without having to select them in a handler function. A corresponding example is given below:

    $(function() ( $.ajax(( success: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo("#row1") ; template.tmpl(data.slice(3)).appendTo("#row2"); ), beforeSend: function(jqxhr, settings) ( settings.url = "mydata.json"; ), context: $("h1 "), complete: function(jqxhr, status) ( var color = status == "success" ? "green" : "red"; this.css("border", "thick solid " + color); ) )); ));

    Here the context parameter is set to a jQuery object containing the h1 elements of the document. In the function defined by the complete parameter, we frame the selected elements (in this case the element, since there is only one h1 element in the document) by calling the css() method on the jQuery object (referenced via this). The border color is determined based on the request status.

    The context parameter can be used to set any object as the context, and you are responsible for performing only valid operations on that object. For example, if you set the context to an HTMLElement, you must pass that object to the $() function before calling any jQuery methods on it.

    Setting basic parameters for Ajax requests

    There is a group of parameters with which you can perform basic setup of an Ajax request (we discussed some of them, url and type, above). Of all the available options, these are the least interesting and their names mostly speak for themselves. The parameters in question are shown in the table below:

    Basic configuration parameters of an Ajax request Parameter Description
    accepts Sets the request to the Accept header, which specifies the MIME types supported by the browser. By default, this value is determined by the dataType parameter
    cache A value of false indicates that the request content should not be cached by the server. By default, all data types except script and jsonp are cached
    contentType Sets the content-tour header value for the request
    dataType Specifies what types of data are expected from the server. If this option is used, jQuery will ignore information provided by the server about the request type
    headers Specifies additional headers and values ​​that should be included in the request
    jsonp Specifies a string to use in place of the callback function when making JSONP requests (cross-domain requests). This parameter requires agreement with the server
    jsonpCallback Specifies the name of the callback function that should be used instead of the auto-generated random name used by jQuery by default
    password Specifies the password that should be used in the request when passing the authentication procedure
    scriptCharset Tells jQuery which character set to use when encoding the requested JavaScript content
    timeout Sets the timeout duration (in milliseconds) for the request
    userName Specifies the username that should be used in the authentication request
    Setting timeouts and headers

    Users often do not even realize that Ajax requests are being executed, and therefore specifying an acceptable timeout duration is not a bad idea, since this will save users from the tedious wait for some unknown process to complete. An example of setting a timeout for a request is given below:

    $(function() ( $.ajax(( timeout: 5000, headers: ( "X-HTTP-Method-Override": "PUT" ), success: function(data) ( var template = $("#flowerTmpl") ; template.tmpl(data.slice(0, 3)).appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ), error: function(jqxhr , status, errorMsg) ( console.log("Error: " + status); ) )); ));

    In this example, the timeout parameter sets the maximum timeout duration to 5 seconds. If the request is not completed within this time, the function specified using the error parameter will be called and the error code specified by the status parameter will be displayed.

    The timer starts immediately after a request is sent to the browser, and most browsers impose limits on the number of requests that can be executed simultaneously. This means that there is a risk that by the time the timeout expires, the request will not even be running. To avoid this, you need to be aware of browser limitations and the size and expected duration of any other Ajax requests that are running.

    Additionally, this example below uses the headers parameter to add a header to the request. The data display object is used to specify headers. The header used here can be useful for creating web applications that support the REST architectural style, as long as the server recognizes it correctly.

    Using additional configuration options

    The following sections describe the most useful and noteworthy advanced options that apply to Ajax requests. They are usually rarely used, but when they are needed, they are indispensable. These options allow you to fine-tune how jQuery interacts with Ajax.

    Creating Synchronous Requests

    The query execution mode is controlled using async parameter. The default value of true for this parameter means that the request will be executed in asynchronous mode, while the value false is synchronous mode.

    When a request is executed synchronously, the ajax() method behaves like a normal function, and the browser proceeds to execute other script instructions only after the request has finished executing.

    Ignoring data that remains unchanged

    By using ifModified parameter It is possible to ensure that data is received only if it has changed since the last request. This behavior is determined by the Last-Modified header. This avoids useless data transfers that will not provide the user with any new information compared to what he already has. By default, ifModified is false, which tells jQuery to ignore the Last-Modified header and provide the data anyway.

    An example of using this parameter is given below:

    $(function() ( $("button").click(function(e) ( $.ajax("mydata.json", ( ifModified: true, success: function(data, status) ( if (status == " success") ( $("#row1, #row2").children().remove(); var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo( "#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ) else if (status == "notmodified") ( $("img").css("border" , "thick solid green"); ) ) )); e.preventDefault(); )) ));

    This example sets the ifModified parameter to true. The success function is always called, but if the content has not changed since the last time it was requested, then the data argument will be undefined and the status argument will be notmodified value.

    In this case, the actions performed are determined by the value of the status argument. If the value of this argument is success, then the data argument is used to add elements to the document. If the status argument is notmodified, then we use the css() method to frame elements that are already in the document.

    In response to the click event associated with the button, the ajax() method is called. This makes it possible to repeat the same query multiple times to demonstrate the effect of the ifModified parameter, as shown in the figure:

    As useful as this option is, I recommend using it with caution. If a request is sent as a result of user action (for example, clicking a button), then there is a possibility that the user clicked the button because the previous request did not complete as expected.

    Imagine that you are requesting data, but the method specified in the success parameter contains an error that prevents the contents of the document from updating correctly. Then your next action will be to try to click the button again to achieve the expected result. If you use the ifModified parameter poorly, you can ignore the user's actions, forcing them to take more serious action to fix the problem.

    Processing response code

    statusCode parameter allows you to select options for further actions depending on the response code to HTTP requests. It can be used either instead of the success and error parameters, or in addition to them. An example of independent use of the statusCode parameter is given below:

    $(function() ( $.ajax(( url: "mydata.json", statusCode: ( 200: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ), 404: function(jqxhr, status, errorMsg) ( $("") .text("Status: " + status + " Error: " + errorMsg) .insertAfter("h1"); ) ) )); ));

    Here, the statusCode parameter is specified as an object that establishes a relationship between response codes for HTTP requests and the corresponding functions that must be executed on the server. Which arguments are passed to functions depends on whether the response code reflects a successful request or an error.

    If the code (for example, 200) corresponds to a successful request, then the arguments are the same as those that would be passed to the function specified by the success parameter. Otherwise (for example, a 404 response code indicating that the requested file was not found), the arguments are the same as those that would be passed to the function specified by the error parameter.

    As you can see, this tool does not provide direct information about response codes. I use it often when debugging browser-server interactions, usually to figure out why jQuery isn't behaving the way I want it to. In this case, I use the statusCode parameter in addition to the success and error parameters and output the information to the console. If these parameters are used together, the success and error functions will be executed first, and then the functions defined by the statusCode parameter will be executed.

    Pre-cleaning response data

    By using dataFilter parameter you can specify a function that will be called to pre-clean the data returned by the server. This tool is indispensable in cases where the data sent by the server is not entirely satisfactory to you, either because it is formatted in an inappropriate way, or because it contains data that you do not want to process.

    This tool helps me a lot when working with Microsoft ASP.NET servers that append extraneous data to JSON data. Removing such data using the dataFilter parameter requires only minimal effort. An example of using the dataFilter parameter is given below:

    $(function() ( $.ajax(( url: "mydata.json", success: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)) .appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2"); ), dataType: "json", dataFilter: function(data, dataType) ( if (dataType = = "json") ( var filteredData = $.parseJSON(data); filteredData.shift(); return JSON.stringify(filteredData.reverse()); ) else ( return data; ) ) )); ));

    The function is passed the data received from the server and the value of the dataType parameter. If dataType is not used, the second argument is set to undefined. Your job is to return the filtered data. In this example, the subject of our attention is data in JSON format:

    Var filteredData = $.parseJSON(data); filteredData.shift(); return JSON.stringify(filteredData.reverse()); ...

    To make the example more illustrative, it performs some additional operations. First, the JSON data is parsed into a JavaScript array using the jQuery parseJSON method. Then the first element is removed from the array using the shift() method, and the order of the remaining elements is reversed using the reverse() method.

    All the function needs to do is return a string, so we call JSON.stringify() knowing that jQuery will convert the data into a JavaScript object before calling the success function. This example demonstrated the ability to remove an element from an array, however, depending on the situation, we could perform any other type of processing.

    The final result is shown in the figure:

    Data transformation management

    I saved a review of one of my favorite settings for last. You may have noticed that jQuery automatically performs some convenient conversions when retrieving certain data types. For example, when receiving JSON data, jQuery provides a success function that uses a JavaScript object rather than the original raw JSON string.

    To manage such transformations it is used converters parameter. The value of this parameter is an object that establishes a mapping between data types and functions used to process them. The example below shows how to use this option to automatically convert HTML data to a jQuery object:

    $(function() ( $.ajax(( url: "flowers.html", // In this example we load HTML markup, not JSON data success: function(data, status, jqxhr) ( var elems = data.filter("div").addClass("dcell"); elems.slice(0, 3).appendTo("#row1"); elems.slice(3).appendTo("#row2"); ), converters: ( "text html": function(data) ( return $(data); ) ) )); ));

    This example registers a function for the text html data type. Note the space between the components of the specified MIME type (as opposed to the text/html notation form). The function accepts data received from the server and returns the converted data. In this case, the data transformation consists of passing the HTML fragment contained in the flowers.html file to the $() function and returning the result. This means that the normal jQuery methods apply to the object passed as the data argument to success.

    When working with data converters, you can get too carried away. I always try to avoid the temptation to do more than I should with these functions. For example, sometimes I'm tempted to apply a template to JSON data and pass back the resulting HTML elements. Although this technique is very convenient, it will not serve you well if someone else tries to extend your code or, for example, you yourself later need to do intensive data processing to get it in its original form.

    Setting up and filtering Ajax requests

    Now that you've become familiar with the ajax() method and the options available to work with it, we can look at a few additional methods that jQuery provides to make it easier to customize requests.

    Defining default settings

    The ajaxSetup() method allows you to set parameter values ​​that will be used by default in all Ajax requests, thereby freeing you from having to configure parameters on each request. An example of using this method is given below:

    ") .text("Status: " + status + " Error: " + errorMsg) .insertAfter("h1"); ), converters: ( "text html": function(data) ( return $(data); ) ) )); $.ajax(( url: "flowers.html", success: function(data, status, jqxhr) ( var elems = data.filter("div").addClass("dcell"); elems.slice( 0, 3).appendTo("#row1"); elems.slice(3).appendTo("#row2"); ) )); ));

    The ajaxSetup() method is called using the jQuery $ function in the same way as the ajax() method was called. The argument to the ajaxSetup() method is an object containing the parameter values ​​that you want to use by default for all Ajax requests. In this example we set default values ​​for the timeout, global, error and converters parameters.

    After the ajaxSetup() method has been called, we only need to define the values ​​of the parameters that we want to change, or those that are not provided by default. This provides significant time savings in cases where you have to make many queries with the same parameter values.

    Request filtering

    The ajaxSetup() method defines basic configuration parameter values ​​that apply to all Ajax requests. The ability to dynamically configure parameters for individual Ajax requests is provided by the ajaxPrefilter() method. An example of using this method is given below:

    $(function() ( $.ajaxSetup(( timeout: 15000, global: false, error: function(jqxhr, status, errorMsg) ( $("") .text("Status: " + status + " Error: " + errorMsg) .insertAfter("h1"); ), converters: ( "text html": function(data) ( return $(data); ) ) ); $.ajaxPrefilter("json html", function(settings, originalSettings , jqxhr) ( if (originalSettings.dataType == "html") ( settings.timeout = 2000; ) else ( jqxhr.abort(); ) )) $.ajax(( url: "flowers.html", dataType: " html", success: function(data, status, jqxhr) ( var elems = data.filter("div").addClass("dcell"); elems.slice(0, 3).appendTo("#row1"); elems.slice(3).appendTo("#row2"); ) )); ));

    The function you specify will be executed for each new Ajax request. The arguments passed to the function are the request parameters (including any default values ​​you set using the ajaxSetup() method), as well as the original parameters passed to the ajax() method (excluding any default values) and the jqXHR request object.

    We make changes to the object passed as the first argument, as shown in the example. In this scenario, if the dataType parameter is present among the parameters passed to the ajax() method, then the timeout duration is set to two seconds. To prevent all other requests from being sent, the abort() method is called on the jqXHR object.

    Script requests are GET only and have difficulty tracking errors. But then - they can be done on any domains,
    which is the main area of ​​application of this transport.

    Any tags can be created via the DOM and added to the document. If you create a node with a link to an external source,
    then when you add a tag to the document, the download process will start. And the server generates the response javascript dynamically and puts the necessary data there.

    The following function adds such a tag to the document, with the required id and src. It adds elements to head, so it won't work if head isn't present.

    Function attachScript(id, src)( var element = dojo.doc.createElement("script") element.type = "text/javascript" element.src = src element.id = id document.getElementsByTagName("head").appendChild (element)

    For example, call

    AttachScript("script1","/service/newMail.js?name=Vasya")

    will add a tag to the head of the document:

    The browser will immediately process the tag: it will request newMail.js from the given URL and execute it.

    When the script is loaded, it must somehow announce itself that the data has been loaded and can be manipulated.

    Usually a callback is used for this, that is, a special function is called at the end of the script.

    To clearly indicate which script should call which callback, the function name is passed as a separate parameter. For example,

    ... // set the handler var handler = function (data) ( ... ) // got the number for the next script handlerId++ // in fact, the callback is not the handler itself, but a service function // which will additionally process successful loading and will clean up the redundant script tag scriptHandlers["script_"+handlerId] = makeHandler(handler) attachScript(handlerId, "/service/newMail.js?name=Vasya&callback=scriptHandlers.script_"+handlerId)

    The server looks at the value of the callback parameter, and adds a call to the script to scriptHandlers.script_XXX, where script_XXX is the value of the callback parameter.

    Typically, the server simply gives the data to the client, responding to the request with a call like

    ScriptHandlers.script_XXX((sender:"Petya",senderId:6))

    This format is called JSONP: JSON with P adding, since javascript objects are used for data exchange (not XML, etc.), and is used
    additional function (padding).

    Sending a large amount of data to the server (Multipart)

    URL length in GET requests is limited. It depends on the browser server, approximately 1kb is a safe value.
    Therefore, to send larger fragments to the server, the multipart protocol is used.

    Each request is supplied with two parameters: a unique ID and part number.

    The first element of the multipart request has part=1, the last one does not have the part parameter. The server can thus count the chunks it receives.

    Communication errors

    Each request creates a timer. If the request is successful, the timer is cleared. After 10 seconds, the timer fires and generates a request error.

    Such processing is much worse than in iframe or XmlHttpRequest, where the server-side error (404,500) becomes immediately visible.

    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 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 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.
      The password that will be used with the 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 to 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 + ) ) );