success php anomaly. Greetings, dear friend! A simple ajax request via jQuery using the AJAX function

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() :

Item 1 Item 2 Item 3 Item 4 Item 5 XML;

Example 5

We use JSON data. Input parameters can be used as attributes of the resulting object.

$.ajax(( dataType: "json", url: "response.php?action=sample5", success: function(jsondata)( $(".results").html("Name = " + jsondata.name + " , Nickname = " + jsondata.nickname); ) ));

The server should return data in JSON format:

$aRes = array("name" => "Andrew", "nickname" => "Aramis"); require_once("Services_JSON.php"); $oJson = new Services_JSON(); echo $oJson->encode($aRes);

We've been introduced to jQuery's direct methods for working with Ajax (such as get(), post(), and load()). This article describes the low-level jQuery Ajax API.

The term low-level might seem to indicate that you're accessing the hidden capabilities of the query engine, but that's not entirely true. The methods described here are less convenient than those discussed previously, but with a little extra effort, you can configure the query to exactly meet your needs, which is not always possible with direct or helper methods.

Simple Ajax requests

Creating queries using a low-level API is not much more difficult than using direct or helper methods. The difference is that this approach allows you to control many other aspects of the request and gain much more information about the request being executed. Central to the low-level API is the ajax() method, a simple example of which is shown below (using the source file and the mydata.json file described in the previous article):

$(function() ( $.ajax("mydata.json", ( success: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo ("#row1"); template.tmpl(data.slice(3)).appendTo("#row2" ));

The ajax() method's arguments are the requested URL and a data display object whose properties define a set of key-value pairs, each of which defines a request parameter. Here, the object passed to the ajax() method contains only one parameter, success, which specifies the function that will be called if the request is successful.

In this example, we request the mydata.json file from the server and use it along with a data template to create elements and insert them into the document, as we did in the previous article using direct methods. By default, the ajax() method creates an HTTP GET request, i.e. this example is equivalent to using the get() and getJSON() methods.

jqXHR object

The ajax() method returns a jqXHR object that can be used to obtain details about the request and with which to interact. The jqXHR object is a wrapper around the XMLHttpRequest object that forms the foundation of browser Ajax support.

For most Ajax operations, the jqXHR object can simply be ignored, which is what I recommend. This object is used in cases where it is necessary to obtain more complete information about the server's response than what can be obtained by other means. It can also be used to configure the parameters of an Ajax request, but this is easier to do using the settings available for the ajax() method. The properties and methods of the jqXHR object are described in the table below:

Properties and methods of the jqXHR object Property/Method Description
readyState Returns an indicator of the request's progress throughout its lifecycle, ranging from 0 (request not sent) to 4 (request completed)
status Returns the HTTP status code sent by the server
statusText Returns a text description of the status code
responseXML Returns the response as XML (if it is an XML document)
responseText Returns the response as a string
setRequest(name, value) Returns the request header (this can be made easier using the headers parameter)
getAllResponseHeaders() Returns as a string all headers contained in the response
getResponseHeaders(name) Returns the value of the specified response header
abort() Aborts the request

The jqXHR object appears in several places in the code. It is first used to save the result returned by the ajax() method, as shown in the example below:

$(function() ( var jqxhr = $.ajax("mydata.json", ( success: function(data) ( var template = $("#flowerTmpl"); template.tmpl(data.slice(0, 3) ).appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2") )); var timerID = setInterval(function() ( console.log("Status: " + jqxhr.status + " " + jqxhr.statusText); if (jqxhr.readyState == 4) ( console.log("Request completed: " + jqxhr.responseText); clearInterval(timerID); ) ), 100); ));

In this example, we store the result returned by the ajax() method and then use the setInterval() method to output request information every 100ms. Using the result returned by the ajax() method does not change the fact that the request is executed asynchronously, so precautions must be taken when working with the jqXHR object. To check the status of the request, we use the readyState property (the value of 4 corresponds to the completion of the request) and display the server response to the console.

For this scenario, the console output looks like this (it may look slightly different in your browser):

I only use the jqXHR object in rare cases and don't do it at all if it is the result returned by the ajax() method. jQuery automatically fires an Ajax request when calling the ajax() method, so I don't find the ability to customize the request parameters to be very useful. If I want to work with the jqXHR object (usually to get more information about the server response), I usually do this through event handler parameters, which we'll talk about next. They provide me with information about the status of the request, which eliminates the need to figure it out.

Setting the request URL

One of the most important options available is url parameter, which allows you to specify a URL for the request. You can use this option as an alternative to passing a URL as an argument to the ajax() method, as shown in the example 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" ));

Creating a POST request

To specify the required type of query to be executed, use type parameter. By default, GET requests are made, as in the previous example. An example of using the ajax() method to create a POST request and submit form data to the server 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"); // Click handler on the "Order" button $("button").click (function(e) ( $.ajax(( url: "phphandler.php", type: "post", data: $("form").serialize(), success: processServerResponse, dataType: "json" )); e.preventDefault() )); function processServerResponse(data) ( // Initially hide all products var inputElems = $("div.dcell").hide(); for (var prop in data) ( // Display only those products , the order of which is greater than 0 // (the response from the server contains only such products) var filtered = inputElems.has("input") .appendTo("#row1").show(); ) // Hiding the basic elements of the form $( "#buttonDiv, #totalDiv").remove(); // Display new elements from the template totalTmpl $("#totalTmpl").tmpl(data).appendTo("body" )); Total orders: $(total) Order .png"/> $(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 previously described url parameter 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 reacted 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 specify an HTMLElement as the context, 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"); , 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");

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.