Fail error ajax

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

$.ajax({
     url: 'does-not-exist.php',
     success: function(returnData){
         var res = JSON.parse(returnData);
     },
     error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }
});

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

  • jqXHR
  • textStatus
  • errorThrown

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

JQuery 3.0: The error, success and complete callbacks are deprecated.

Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.

An example of done and fail being used:

$.ajax("submit.php")
  .done(function(data) {
      //Ajax request was successful.
  })
  .fail(function(xhr, status, error) {
      //Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText
      alert('Error - ' + errorMessage);
})

Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.

Hopefully, you found this tutorial to be useful.

Содержание

  1. Handling Ajax errors with jQuery.
  2. JQuery 3.0: The error, success and complete callbacks are deprecated.
  3. One thought on “ Handling Ajax errors with jQuery. ”
  4. .ajaxError()
  5. .ajaxError( handler ) Returns: jQuery
  6. version added: 1.0 .ajaxError( handler )
  7. Additional Notes:
  8. Example:
  9. Books
  10. jQuery.ajax()
  11. jQuery.ajax( url [, settings ] ) Returns: jqXHR
  12. version added: 1.5 jQuery.ajax( url [, settings ] )
  13. version added: 1.0 jQuery.ajax( [settings ] )
  14. The jqXHR Object
  15. Callback Function Queues
  16. Data Types
  17. Sending Data to the Server
  18. Advanced Options

Handling Ajax errors with jQuery.

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

JQuery 3.0: The error, success and complete callbacks are deprecated.

Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.

An example of done and fail being used:

Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.

Hopefully, you found this tutorial to be useful.

One thought on “ Handling Ajax errors with jQuery. ”

thanks its helpful 🙂 many of us not aware of error block in ajax

Источник

.ajaxError()

.ajaxError( handler ) Returns: jQuery

Description: Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.

version added: 1.0 .ajaxError( handler )

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

To observe this method in action, set up a basic Ajax load request.

Attach the event handler to the document:

Now, make an Ajax request using any jQuery method:

When the user clicks the button and the Ajax request fails, because the requested file is missing, the log message is displayed.

All ajaxError handlers are invoked, regardless of what Ajax request was completed. To differentiate between the requests, use the parameters passed to the handler. Each time an ajaxError handler is executed, it is passed the event object, the jqXHR object (prior to jQuery 1.5, the XHR object), and the settings object that was used in the creation of the request. When an HTTP error occurs, the fourth argument ( thrownError ) receives the textual portion of the HTTP status, such as «Not Found» or «Internal Server Error.» For example, to restrict the error callback to only handling events dealing with a particular URL:

Additional Notes:

  • As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxError() method, must be attached to document .
  • If $.ajax() or $.ajaxSetup() is called with the global option set to false , the .ajaxError() method will not fire.

Example:

Show a message when an Ajax request fails.

Books

Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

Источник

jQuery.ajax()

jQuery.ajax( url [, settings ] ) Returns: jqXHR

Description: Perform an asynchronous HTTP (Ajax) request.

version added: 1.5 jQuery.ajax( url [, settings ] )

version added: 1.0 jQuery.ajax( [settings ] )

Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.

When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false . For example, < a: «bc», d: «e,f» >is converted to the string «a=bc&d=e%2Cf» . If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, < a: [1,2] >becomes the string «a%5B%5D=1&a%5B%5D=2» with the default traditional: false setting.

When data is passed as a string it should already be encoded using the correct encoding for contentType , which by default is application/x-www-form-urlencoded .

In requests with dataType: «json» or dataType: «jsonp» , if the string contains a double question mark ( ?? ) anywhere in the URL or a single question mark ( ? ) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745 ).

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

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

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

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

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

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

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

The jqXHR Object

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

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

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

    jqXHR.done(function( data, textStatus, jqXHR ) <>);

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

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) <>);

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

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

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

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

jqXHR.then(function( data, textStatus, jqXHR ) <>, function( jqXHR, textStatus, errorThrown ) <>);

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

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

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

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

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

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

Callback Function Queues

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

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

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

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

Data Types

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

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

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

If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument , to the success handler. The XML document is made available through the responseXML property of the jqXHR object.

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.

If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.

For more information on JSONP, see the original post detailing its use.

Sending Data to the Server

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

Advanced Options

The global option prevents handlers registered using .ajaxSend() , .ajaxError() , and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend() if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false . See the descriptions of these methods below for more details.

If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.

Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.

By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false . To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true .

The scriptCharset allows the character set to be explicitly specified for requests that use a

Источник

jQuery ajax fail

Introduction to jQuery ajax fail

The jQuery ajax fail is an ajax event which is only called if the request fails. The AJAX fail is a global event that triggered on the document to call handler function, which may be listening. The ajax fail can be performed with the help of the ajaxError() function. The jQuery ajaxError() function is a built-in function in jQuery. The function specified by the ajaxError() function is called when the request fails or generates the errors. We can use the fail() callback function as well on the JavaScript promise object( the jqXHR object return by the $.ajax() function) to run the specific function on the ajax request fail.

The syntax of the jQuery ajaxError() function –

$(document).ajaxError(function(event, xhr, options, exc));

Parameters –

function(event, xhr, options) – This is not an optional parameter. It specifies the callback function, which will be executed when the sent request fails; it accepts four parameters event, xhr, and options. The event parameter represents the event object. The parameter xhr represents XMLHttpRequest object. The parameter option represents the options used in the ajax request. The last parameter exc would represent the javaScript exception if it occurred.

Return value –

The return value of this function is XMLHttpRequest object.

Working of ajaxError() function

The jQuery ajaxError() function accepts four parameters. Suppose we have to do the asynchronous HTTP GET request to load the data from the server and on the fail of the request (unsuccessfully complete), call the function to display some message to notify the request is fail. So we can use the ajaxError() function as

$(document).ajaxError(function(event, request, settings) { $( "#p2" ).html( "<h1>Request Fail.</h1>"); });”,

which display the message “Request Fail” on the fails of the request.

Examples for the jQuery ajaxError() function

Here are the following examples mention below

Example #1

Example of jQuery ajaxError() function to load the data by using ajax request from the specified location and on the fail of the request display notification message –

Code:

<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<title> This is an example for jQuery ajax Error() function </title>
</head>
<body>
<h3> This an example of jQuery ajax fail: </h3>
<button id = "btn" > Load and call the ajaxError() function </button>
<br>
<p id = "p1" style = "color : red"> </p>
<p id = "p2" style = "color : red"> </p>
<script>
$( document ).ready( function(){
$( document ).ajaxError( function(){
$( "#p1" ).text("An error occurred!");
});
$( "#btn").click( function(){
$( "#p2" ).load( "wrongfile.txt");
});
});
</script>
</body>
</html>

An output of the above code is –

jQuery ajax fail output 1

Once we click on the “Load and call the ajaxError() function” button, the output is –

jQuery ajax fail output 1.2

In the above code, when we click on the button, the load() function will call, which sends the ajax request to the server to get the data. The load() function load the data from the server and put the loaded data to the selected element if the request is successful. If the request fails the ajaxError() function display the notification message as “$(document).ajaxError(function(){ $(“#p1”).text(“An error occurred!”);});”. So, once the ajax request fails, the “An error occurred!” Message will be displayed, as we can see in the above output.

Example #2

Example of jQuery ajaxError() function to load the data by using ajax request from the specified location and on the fail of the request display notification message with the global ajaxError() callback function –

Code:

<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<title> This is an example for jQuery ajax fail</title>
</head>
<body>
<h3> This an example of jQuery ajax fail: </h3>
<button id = "Btn" > Send the ajax request which will fail. </button>
<br>
<p style = "color : red"> </p>
<script type = "text/javascript">
$(document).ready( function () {
$('#Btn').click( function(){
// url is not correct to get the data, because of which the request will fail
var ajxReq = $.ajax( 'http://time.com', {
contentType : 'application/json',
dataType : 'json',
timeout : 600
});
ajxReq.success( function ( data, status, jqXhr ) {
$( "p" ).append( "First data is : " + data.date  + ".<br> Second data is : " + data.milliseconds_since_epoch  + ".<br> Thirs data is : " + + data.time );
});
ajxReq.error( function ( jqXhr, textStatus, errorMessage ) {
$( "p" ).append( "The Status is : " + textStatus);
});
});
});
</script>
</body>
</html>

An output of the above code is –

jQuery ajax fail output 2

Once we click on the “Load and call the ajaxsuccess() function” button, the output is –

jQuery ajax fail output 2.2

In the above code, when we click on the button, the load() function will call, which sends the ajax request to the server to get the data. The load() function load the data from the server and put the loaded data to the selected element. But if the request is fails the global ajaxError() callback function used to shows the status of the request as “ajxReq.error( function ( jqXhr, textStatus, errorMessage ){$(“p”).append(“The Status is : ” + textStatus);});”. So, once the ajax request fails, the request status will be display; as we can see in the above output, the request status is an error.

Example #3

Example of jQuery ajaxError() function to load the data by using ajax request from the specified location and on the fail of the request display notification message with the fail() callback function –

Code:

<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<title> This is an example for jQuery ajax fail</title>
</head>
<body>
<h3> This an example of jQuery ajax fail : </h3>
<button id = "Btn" > Send the ajax request which will fail. </button>
<br>
<p style = "color : red"> </p>
<script type = "text/javascript">
$(document).ready( function () {
$('#Btn').click( function(){
// url is not correct to get the data, because of which the request will fail
$.ajax({
url: "/app-url/",
type: "GET",
dataType: 'json',
})
.done (function(data, textStatus, jqXHR) {
alert("The request success is : " + response);
})
.fail (function(jqXHR, textStatus, errorThrown) {
alert("The request generate error");
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
alert("The request is complete");
});
});
});
</script>
</body>
</html>

An output of the above code is –

output 3

Once we click on the button, the output is –

output 3.2

Click on the ok button, the output is –

output 3.3

In the above code, when we click on the button, the load() function will call, which sends the ajax request to the server to get the data. But if the request is fails the fail() callback function used to call on the jqXHR object return by the ajax() function and display the notification message of the request as “.fail (function(jqXHR, textStatus, errorThrown) { alert(“The request generate error”); })”. So, once the ajax request fails, the alert message will be displayed, as we can see in the above output.

Conclusion – jQuery ajax fail

The jQuery ajaxError() function is a built-in function in jQuery, which is used to specifies a handler function to be run when the ajax request fails.

Recommended Articles

This is a guide to jQuery ajax fail. Here we discuss the Working of the ajaxError() function along with the examples and output. You may also have a look at the following articles to learn more –

  1. jQuery prev
  2. jQuery Array
  3. jQuery Merge
  4. jQuery ajax headers

Описание: Выполняет асинхронный HTTP (Ajax) запрос.

Функция $.ajax() лежит в основе всех Ajax запросов отправляемых при помощи jQuery. Зачастую нет необходимости вызывать эту функцию, так как есть несколько альтернатив более высого уровня, такие как $.get() и .load(), которые более простые в использовании. Если требуется менее распространенные варианты , через, $.ajax() Вы можете более гибко скофигурировать запрос.

В простейшем виде, функция $.ajax() может быть вызвана без аргументов:

Важно: настройки по умолчанию могут быть установлены при помощи функции $.ajaxSetup().

Этот пример, не используюя никаких параметров, загружает содержимое текущей страницы, но ничего не делает с результатом. Для использования результата, Вы можете реализовать одну из функция обратного вызова.

Объект jqXHR

Объект jQuery XMLHttpRequest (jqXHR) возвращается функцией $.ajax() начиная с jQuery 1.5 является надстройкой над нативным объектом XMLHttpRequest. Например, он содержит свойства responseText и responseXML, а также метод getResponseHeader(). Когда траспортом используемым для запрос является что то иное, а не XMLHttpRequest (например, тэг script tag для JSONP запроса) объект jqXHR эмулирует функционал нативного XHR там где это возможно.

Начиная с jQuery 1.5.1, объект jqXHR также содержит метод overrideMimeType() (он был доступен в jQuery 1.4.x, но был временно удален в версии jQuery 1.5). Метод .overrideMimeType() может быть использован в обработчике beforeSend(), например, для изменения поля заголовка content-type:

1

2

3

4

5

6

7

8

9

10

11

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

beforeSend: function( xhr ) {

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

if ( console && console.log ) {

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

Объект jqXHR возвращаемый методом $.ajax() в версии jQuery 1.5 реализует интерфейс Promise, дающий ему все свойства, методы и поведение Promise. Эти методы принимают один или несколько аргументов, которые вызываются при завершении запроса инициированного при помощи $.ajax(). Это позволяет назначать несколько обработчиков на один запрос и даже назначать обработчики после того как запрос может быть завершен. (Если запрос уже выполнен, то обработчики вызовутся немедленно). Доступные методы Promise в объекте jqXHR:

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

    Альтернатива создания обработчика success, подробнее смотрите на deferred.done().

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

    Альтернатива создания обработчика error, метод .fail() заменяет устаревший метод .error(). Смотрите подробнее deferred.fail().

  • jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (добавлен в версии jQuery 1.6)

    Альтернатива создания обработчика complete, метод .always() заменяет устаревший метод .complete().

    В ответ на успешный запрос, аргументы функции те же самые что и у .done(): data, textStatus и объект jqXHR. Для ошибочных зпросов аргументы те же самые что и у .fail(): объект jqXHR, textStatus и errorThrown. Смотрите подробнее deferred.always().

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

    Включает в себя функциональность методов .done() и .fail(), что упрощает (начиная с jQuery 1.8) проще управлять объектом Promise. Смотрите подробнее deferred.then().

Внимание: обработчики jqXHR.success(), jqXHR.error() и jqXHR.complete() будут удалены в jQuery 3.0. Вы можете использовать jqXHR.done(), jqXHR.fail() и jqXHR.always() соответственно.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// Назначаем обработчики сразу после выполнения запроса

// и сохраняем объект jqXHR для этого запроса

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

// Установим другой обработчик выполнения запроса

jqxhr.always(function() {

alert( "second complete" );

Ссылка this внутри всех обработчиков указывает на объект заданный в параметре context переданные в аргумент settings метода $.ajax; если context не указан, то this указывает на объект settings.

Для обеспечения обратной совместимости с кодом XMLHttpRequest, в объекте jqXHR предоставляет следующие свойства и методы:

  • readyState
  • status
  • statusText
  • responseXML и/или responseText когда запрос вернул xml и/или text, соответственно
  • setRequestHeader(name, value) те заголовки что отходят от стандарта, заменят старое значение на новое, а не конкатенируют старое и новые значения
  • getAllResponseHeaders()
  • getResponseHeader()
  • statusCode()
  • abort()

Механизма onreadystatechange не предусмотрено, так как done, fail, always и statusCode охватывает все возможные требования.

Очередность функций обратного вызова

Все параметры beforeSend, error, dataFilter, success и complete принимают в качестве значений функции обратного вызова, которые вызываются в соотвествующие моменты времени.

С версии jQuery 1.5 функции fail и done, и, начиная с jQuery 1.6, always вызовутся в первую очередь, первыми из упрвляемой очереди, что позволяет более чем один обработчик для каждого элемента очереди. Смотрите отложенные методы, которые реализуют внутренности обработчиков метода $.ajax().

Функции обратного вызова предоставленные методом $.ajax() следующие:

  1. beforeSend вызывается всегда; принимает jqXHR объект и объект settings как параметры.
  2. error вызывается, если запрос выполняется с ошибкой. Принимает объект jqXHR, строку со статусом ошибки и объект исключения если применимо. Некоторые встроенные ошибки обеспечивают строку качестве объекта исключения: «abort», «timeout», «No Transport».
  3. dataFilter вызывается немедленно при успешном получении данных ответа. Принимает в качестве параметров возвращенные данные и знчение параметра dataType и должен вернуть (возможно измененные данные) для передачи далее в обработчик success.
  4. success вызывается если запрос выполнен успешно. Принимает данные ответа, строку содержащую код успеха и объект jqXHR.
  5. Promise обработчик.done(), .fail(), .always() и .then() — выполняются, в том порядке в котором зарегистрированы.
  6. complete вызывается когда запрос закончен, независимо от успеха или неудачи выполнения запроса. Принимает объект jqXHR, отформатированную строку со статусом успеха или ошибки.

Типы данных

Различные типы ответа на вызов $.ajax() подвергаются различным видам предварительной обработки перед передачей обработчика success. Тип предварительной подготовки зависит от указанного в ответе поля заголовка Content-Type, но может быть явно указан при помощи опции dataType. Если параметр dataType задан, то поле заголовка Content-Type будет проигнорирован.

Возможны следующие типы данных: text, html, xml, json, jsonp и script.

Если указан text или html, никакой предварительной обработки не происходит. Данные просто передаются в обработчик success и доступны через свойство responseText объекта jqXHR.

Если указан xml, то ответ парсится при помощи jQuery.parseXML перед передачей в XMLDocument в обработчик success. XML документ доступен через свойство responseXML объекта jqXHR.

Если указан json, то ответ парсится при помощи jQuery.parseJSON перед передачей в объект для обработчика success. Полученный JSON объект доступен через свойство responseJSON объекта jqXHR.

Если указан script, то $.ajax() выполнит JavaScript код который будет принят от сервере перед передачей этого кода как строки в обработчик success.

Если указан jsonp, $.ajax() автоматически добавит в строку URL запроса параметр (по умолчанию) callback=?. Параметры jsonp и jsonpCallback из объекта settings переданных в метод $.ajax() могут быть использованы для указания имени URL-параметра и имени JSONP функции обратного вызова соответственно. Сервер должен вернуть корректный Javascript который будет переда в обработчик JSONP. $.ajax() выполнит возвращенный JavaScript код, вызвыв функцию JSONP по ее имени, перед передачей JSON объекта в обработчик success.

Отправка данных на сервер

По умолчанию, Ajax запросы отправляются при помощи GET HTTP метода. Если POST метод требуется, то метод следует указать в настройках при помощи параметра type. Этот параметр влияет на то как данные из параметра data будут отправлены на сервер. Данные POST запроса всегда будут переданы на сервере в UTF-8 кодировкепо стандарту W3C XMLHTTPRequest.

Параметр data может содержать строку произвольной формы, например сериализованная форма key1=value1&key2=value2 или Javascript объект {key1: 'value1', key2: 'value2'}. Если используется последний вариант, то данные будут преобразованы в строку при помощи метода jQuery.param() перед их отправкой. Эта обработка может быть отключена при помощи указания значения false в параметре processData. Обработка может быть нежелательной, если Вы хотите отправить на сервере XML документ, в этом случае измените параметр contentType с application/x-www-form-urlencoded на более подходящий MIME тип.

Расширенные настройки

Параметр global предотвращает выполнение обработчиков зарегистрированных при помощи методов .ajaxSend(), .ajaxError() и подобных методов. Это может быть полезно, например, для скрытия индикатора загрузки реализованного при помощи .ajaxSend() если запросы выполняются часто и быстро. С кросс-доменными и JSONP запросами, параметр global автоматически устанавливается в значение false.

Если сервер выполняет HTTP аутентификацию перед предоствлением ответа, то имя пользователя и пароль должны быть отправлены при помощи параметров username и password options.

Ajax запросы ограничены по времени, так что ошибки могут быть перехвачены и обработаны, чтобы обеспечить наилучшее взаимодействие с пользователем. Таймауты запроса обычно либо установлены по умолчанию, либо установлены глобально при помощи $.ajaxSetup() вместо того чтобы указывать параметр timeout для каждого отдельного запроса.

По умолчанию, запросы всегда совершаются, но браузер может предоставить ответ из своего кэша. Для запрета на использования кэшированных результатов установите значение параметра cache в false. Для того чтобы вызвать запрос с отчетом об изменении ресурса со времени последнего запроса установите значение параметра ifModified в true.

Параметр scriptCharset разрешает кодировку которая будет явно использована в запросах использующих тэг <script> (то есть тип данных script или jsonp). Это применимо в случае если удаленный скрипт и Ваша текущая страница используют разные кодировки.

Первая буква в слове Ajax означает «асинхронный», что означает что операция происходит параллельно и порядок ее выполнения не гарантируется. Параметр async метода $.ajax() по умолчанию равен true, что указывает что выполнение кода может быть продолжено после совершения запроса. Установка этого параметра в false (и следовательно, не делая Ваш вывод более асинхронным) настоятельно не рекомендуется, так как это может привести к тому что браузер перестанет отвечать на запросы.

Метод $.ajax() вернет объект XMLHttpRequest который и создает. Обычно jQuery обрабатывает создание этого объекта внутри, но можно указать при помощи параметра xhr функция которая переопределит поведение по умолчанию. Возвращаемый объект обычно может быть отброшен, но должен обеспечивать интерфейс низкого уровня для манипуляции и управления запросом. В частности, вызов .abort() на этом объекте должен будет остановить запрос до его завершения.

Расширение Ajax

Начиная с jQuery 1.5, реализация Ajax в jQuery включает предварительные фильтры, транспорты и преобразователи, которые позволят Вам очень гибко настроить Ajax запросы под любые нужды.

Использование преобразований

$.ajax() преобразователи поддерживают трансформацию одних типов данных другие. Однако, если Вы хотите трансформировать пользовательский тип данных в известный тип данных (например json), Вы должны добавить добавить соответствие между Content-Type ответа и фактическим типом данных, используя параметр contents:

1

2

3

4

5

6

7

8

9

10

11

mycustomtype: /mycustomtype/

"mycustomtype json": function( result ) {

Этот дополнительный объект необходим, потому что Content-Types ответа и типы данных никогда не имеют однозначного соответствия между собой (отсюда и регулярное выражение).

Для преобразования из поддерживаемого типа (например text или json) в пользовательский тип данных и обратно, используйте другой сквозной преобразователь:

1

2

3

4

5

6

7

8

9

10

11

12

mycustomtype: /mycustomtype/

"text mycustomtype": true,

"mycustomtype json": function( result ) {

Пример выше позволяет перейти из text в mycustomtype и затем из mycustomtype в json.

  • Связанные категории:
  • Ajax
    » Low-Level Interface

Returns: jqXHR

Выполняет асинхронный HTTP (Ajax) запрос

  • version added: 1.5jQuery.ajax( url [, settings] )

    url
    Тип: Строка
    URL адрес, на который будет отправлен Ajax запрос

    settings
    Тип: Объект
    Набор параметров вида ключ / значение, которые настраивают запрос Ajax. Все настройки опциональны. По умолчанию настройки берутся из $.ajaxSetup(). Ниже приведен полный список всех настроек.

  • version added: 1.0jQuery.ajax( settings )

    settings
    Тип: Объект
    Набор параметров вида ключ / значение, которые настраивают запрос Ajax. Все настройки опциональны. По умолчанию настройки берутся из $.ajaxSetup().

settings:

Настройка Тип данных
accepts

По умолчанию: зависит от типа данных

При выполнении ajax-запроса, в заголовках (header) указываются допустимые типы содержимого, ожидаемого от сервера. Значения этих типов будут взяты из параметра accepts. Если требуется его изменить, лучше сделать это с помощью метода $.ajaxSetup().

объект
async

По умолчанию: true

По умолчанию, все запросы отсылаются асинхронно (значение данного параметра true). Если же вам нужны синхронные запросы, то параметру async выставите значение false. Кроссдоменные запросы и dataType: «jsonp» не выполняются в синхронном режиме. Учтите, синхронные запросы могут на время выполнения запроса заблокировать браузер.

логический
beforeSend(jqXHR jqXHR, объект settings)

Функция, которая будет вызвана непосредственно перед отправкой ajax-запроса на сервер. Она может быть использована для модификации jqXHR-объекта (в ранних версиях, до jQuery 1.4.x использовался XMLHttpRequest). Так же может использоваться для изменения заголовков (headers) и т.д. Объект типа jqXHR и объект настроек, передаются в качестве аргументов. Возврат значения false в функции beforeSend вызовет отмену ajax-запроса. Начиная с jQuery 1.5, beforeSend сработает вне зависимости от типа запроса.

функция
cache

По умолчанию: true, false для типов данных ‘script’ and ‘jsonp’

Если false, запрашиваемая страница не будет кэшироваться браузером.

логический
complete(jqXHR jqXHR, строка textStatus)

Функция, которая будет вызвана после завершения ajax запроса (срабатывает после функций-обработчиков success и error). Функция принимает два аргумента: объект типа jqXHR (в ранних версиях, до jQuery 1.4.x использовался XMLHttpRequest) и строку, характеризующую статус запроса («success», «notmodified», «error», «timeout», «abort», или «parsererror»). Начиная с jQuery 1.5, complete может принимать массив функций.

функция или массив
contents

Параметр задается в формате {строка:регулярное выражение} и определяет, как jQuery будет разбирать ответ от сервера, в зависимости от его типа. (добалено в версии 1.5) 

объект
contentType

По умолчанию: ‘application/x-www-form-urlencoded; charset=UTF-8’

При отправке Ajax запроса, данные передаются в том виде, в котором указаны в данном параметре. По умолчанию используется ‘application/x-www-form-urlencoded; charset=UTF-8’. Если задать значение самим, то оно будет отправлено на сервер. Если кодировка не указана, то по умолчанию будет использоваться кодировка выставленная на сервере.

строка
context

Объект, который станет контекстом после выполнения запроса (передаваемое значение в переменную this). Например, если указать в качестве контекста DOM-элемент, то все обработчики ajax-запроса тоже будут выполняться в контексте данного DOM-элемента. В данном примере ключевое слово this будет содержать document.body:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});    
    
объект
converters

По умолчанию: {«* text»: window.String, «text html»: true, «text json»: jQuery.parseJSON, «text xml»: jQuery.parseXML}

Определяет, с помощью каких функций будет производиться конвертация значений из одного типа, в другой. (добалено в версии 1.5)

объект
crossDomain

По умолчанию: false для одного и того же домена, true для кроссбоменных запросов.

Если вы хотите, чтобы выполнить кросс-доменный запрос (например, JSONP) на том же домене, выставите true в настройке crossDomain. Это позволяет, например, сделать серверные перенаправление на другой домен. (добалено в версии 1.5)

логический
data

Данные, которые будут переданы на сервер. Если данные не являются строкой, то они конвертируются в строку запроса. Для запросов типа GET данные прикрепляются к URL. Объект должен состоять из пар ключ/значение. Если в значении массив, то jQuery упорядочивает значения в зависимости от настройки traditional. По умолчанию, например, {foo:[«bar1», «bar2»]} превращается в &foo=bar1&foo=bar2.

объект или строка
dataFilter(строка data, строка type)

Функция, с помощью которой будут обрабатываться сырые данные типа XMLHttpRequest, полученные от сервера. Ваша функция должна играть роль фильтра и возвращать очищенную строку. В функцию передаются два параметра: полученные данные и значение параметра dataType.

функция
dataType

По умолчанию: автоматически определяемая строка (xml, json, script, или html)

Тип данных, ожидаемых от сервера. Если опция не определена, то jQuery попытается определить тип, основываясь на MIME-типе ответа. 

строка
error(jqXHR jqXHR, строка textStatus, строка errorThrown)

Функция, исполняемая в случае неудачного запроса. Принимает 3 аргумента: объект jqXHR (в прошлом XMLHttpRequest), строку с описанием ошибки, а так же строку исключения, если оно было выбрашено. Второй аргумент может содержать следующие значения: null, «timeout», «error», «abort», и «parsererror». В случае если происходит HTTP ошибка, то в третий аргумент будет записан её текстовой статус.  К примеру, «Not Found» или «Internal Server Error.». Начиная с jQuery 1.5, вместо одной функции, этот параметр может принимать массив функций. Событие error не происходит при dataType равному script или JSONP.

функция или массив
global

По умолчанию: true.

Вызывать или нет глобальные обработчики событий Ajax для этого запроса (например ajaxStart или ajaxStop).

логический
headers

По умолчанию: {}

Здесь можно указать дополнительные заголовки запроса (header). Значения этой настройки будут введены до вызова функции beforeSend, в которой могут быть внесены окончательные изменения в заголовки. (добалено в версии 1.5)

объект
ifModified

По умолчанию: false

Запрос будет считаться успешным только в случае, если данные ответа изменились со времени последнего запроса. Проверка осуществляется по заголовку Last-Modified. По умолчани, данная опция отключена. В jQuery 1.4 так же проверяется значение ‘etag’, для отслеживания факта изменения данных.

логический
isLocal

По умолчанию: в зависимости от текущей локации

Параметр определяет, запущена ли веб-страница локально (например по протоколу file, *-extension, и widget) или нет (например по протоколу http). Данную настройку лучше менять с помощью метода $.ajaxSetup(). (добалено в версии 1.5)

логический
jsonp

Определяет имя параметра, который добавляется в url JSONP-запроса(по умолчанию, используется «callback»). К примеру настройка {jsonp:’onJSONPLoad’} преобразуется в часть url строки ‘onJSONPLoad=?’. Начиная с версии 1.5, указание в этом параметре false предотвращает добавление в url дополнительного параметра. В этом случае, необходимо установить значение настройки jsonpCallback. Например так: {jsonp:false, jsonpCallback:»callbackName»}.

строка
jsonpCallback

Функция, которая будет вызвана при ответе сервера на запрос типа JSONP. По умолчанию, jQuery генерирует произвольное уникальное имя этой функции, что более предпочтительно. Если вы хотите использовать кэширование GET запросов, то вписывайте название функции сами. Начиная с версии 1.5 можно указать функцию, для того, чтобы обработать ответ сервера самостоятельно.

строка или функция
mimeType

Здесь можно указать тип данных,  в котором ожидается ответ от сервера вместо XHR. (добалено в версии 1.5.1)

строка
password

Пароль, который будет использоваться в ответ на запрос проверки подлинности доступа HTTP (если это требуется)

строка
username

Имя пользователя, которое будет использоваться в ответ на запрос проверки подлинности доступа HTTP (если это требуется)

строка
processData

По умолчанию: true;

По умолчанию передаваемые на сервер данные преобразуются из объекта в строку запроса и отправляются как «application/x-www-form-urlencoded». Если вам необходимо отправить DOM-документ или иные данные, которые нельзя подвергать конвертированию установите опцию processData в false.

логический
scriptCharset

Применяется только для Ajax GET-запросов типов ‘JSONP’ и ‘script ‘. Если сервер на стороннем домене использует кодировку, отличную от вашей, необходимо указать кодировку стороннего сервера.

строка
statusCode

По умолчанию: {}

Набор пар, в котором кодам выполнения запроса сопоставляются функции, которые при этом будет вызваны. Например, для кода 404 (страницы не существуют) можно сделать вывод сообщения на экран:

$.ajax({
  statusCode:{
    404:function(){
      alert('Страница не найдена');
    }
  }
});    

Если запрос прошёл успешно, то в качестве параметра, анонимная функция будет принимать те же параметры, что и при success. При ошибке, будет принимать то же самое что и при функции-обработчике error. (добалено в версии 1.5)

объект
success(объект data, строка textStatus, объект jqXHR)

Функция, которая будет вызвана в случае успешного завершения запроса. Принимает 3 аргумента — данные (data), присланные сервером и прошедшие предварительную обработку; строка со статусом выполнения (textStatus); объект jqXHR (в версиях до 1.5 вместо jqXHR используетсяXMLHttpRequest). С версии jQuery 1.5, вместо одной функции, этот параметр может принимать массив функций.

функция или массив
timeout

Время ожидания ответа от сервера в миллисекундах. Переписывает глобальную настройку этого же параметра в $.ajaxSetup(). Если это время будет превышено, запрос будет завершен с ошибкой и произойдет событие error, которое будет иметь статус «timeout».

число
traditional

По умолчанию: false

Установите значение этого параметра в true, для того, чтобы использовать традиционный стиль сериализации.

логический
type

По умолчанию: GET

Определяет тип запроса GET или POST. Можно также использовать другие HTTP-запросы (такие как PUT или DELETE), но следует помнить, что они поддерживаются не всеми бразерами.

строка
url

По умолчанию: текущая страница.

Страница, накоторую будет отправлен запрос.

строка
xhr

По умолчанию ActiveXObject в IE, XMLHttpRequest в других браузерах.

Callback-функция, для создания объекта XMLHttpRequest. Создав свою функцию, вы берёте на себя всю ответственность за формирование объекта.

function
xhrFields

Объект вида {имя:значене} для изменения значений соответствующих полей объекта XMLHttpRequest.

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

(добалено в версии 1.5.1)

map

Примеры

Сохранить данные на сервере и оповестить об этом пользователя.

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

Получить последнюю версию HTML страницы

$.ajax({
  url: "test.html",
  cache: false
}).done(function( html ) {
  $("#results").append(html);
});

Передаём в качестве данных XML документ. Отключаем автоматическую конвертацию данных в обычную строку, задав настройке processData значение false:

var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
  url: "page.php",
  processData: false,
  data: xmlDocument
});
 
xmlRequest.done(handleResponse);

Отправить на сервер значение ID. Сохранить данные, оповестить пользователя. Если запрос не прошёл, сообщить об этом пользователю.

var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});
 
request.done(function(msg) {
  $("#log").html( msg );
});
 
request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

Загрузить и выполнить файл JavaScript:

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

Связанные уроки:

  • Создание простого AJAX сайта с помощью jQuery

    В сегодняшнем уроке мы создадим простой сайт с помощью jQuery.

  • Что нового в jQuery 1.5?

    Совсем недавно, как и было обещано, группа разработчиков библиотеки jQuery выпустила новую версию своего продукта. Я попытаюсь вам рассказать о фитчах, которые вошли в свежий релиз.

Learn to utilize the full power of AJAX with jQuery to make application development easy, fast as well as effective.

Table of Contents

$.ajax() Method
jqXHR (jQuery XMLHttpRequest) vs. XHR (XMLHttpRequest)
Invoking jQuery Ajax HTTP Methods
Synchronous vs. Asynchronous Communication
jQuery Ajax Global Event Handlers
	$.ajaxSend()
	$.ajaxStart()
	$.ajaxStop()
	$.ajaxSuccess()
	$.ajaxError()
	$.ajaxComplete()
Using $.ajaxSetup() to Globalize Parameters
Using $.ajaxPrefilter() to filter Ajax Requests
Other Ajax Powered Functions in jQuery
	$.get() and $.post() Functions
	$.load() Function
	$.getScript()

$.ajax() Method

In the root of jQuery Ajax is ajax() function. This function is used to perform HTTP requests which are by default asynchronous. The syntax for using this function is:

$.ajax({name:value, name:value, ... })

The parameters specifies one or more name/value pairs for the AJAX request. Possible names/values in the table below:

Name Value/Description
async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true. Please note that as of jQuery 1.8, the use of async: false is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions)
contentType The content type used when sending data to the server. Default is: “application/x-www-form-urlencoded”
context Specifies the “this” value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object

jQuery AJAX Example (below v1.8)

In the given example, we can make a sample ajax request like this (till version jQuery 1.7).

$.ajax({
	url: "/app-url/relative-url", 
	data: {
        name : "The name",
        desc : "The description"
    },
	success: function(data, textStatus, jqXHR)
	{
    	alert("Success: " + response); 
	},
	error: function(jqXHR, textStatus, errorThrown)
	{
    	alert("Error"); 
	}
});

jQuery AJAX Example (since v1.8)

In the given example, we can make a sample ajax request like this (in version jQuery 1.8 and above).

$.ajax({
    url: "/app-url/relative-url",
    data: {
        name : "The name",
        desc : "The description"
    }
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

jqXHR (jQuery XMLHttpRequest) vs. XHR (XMLHttpRequest)

jQuery 1.8 has brought a major change in how ajax are mode through jQuery. This change is the return type of $.ajax() method. Previously till version 1.7, return type was XHR i.e. XMLHttpRequest, but from version 1.8 it’s jqXHR i.e. jQuery XMLHttpRequest.

In jQuery 1.8, library wraps the browser native XMLHttpRequest object with a superset API and return jqXHR object. jqXHR object simulates native XHR functionality as well as provides some more features e.g.

  • It handles the HTTP request headers (Last-Modified, etag, Content-Type, MIME types etc…)
  • It handles the callbacks of the request (including promise callbacks .done(), .fail() etc…)
  • It handles any pre-filters set for the request
  • It handles any timeouts set for the request
  • It handles any cross domain calls (including jsonp)

The jqXHR objects returned by $.ajax() implement the Promise interface. The object has all the properties, methods, and behavior of a Promise.

jQuery library writers have made efforts to make it backward compatible yet it does no support onreadystatechange() method.

Invoking HTTP Methods

Let’s see how different HTTP methods can be invoked by jQuery ajax. I am just writing the skeleton of code, you are expected to change the code as per your needs.

jQuery Ajax HTTP GET or DELETE Method

$.ajax({
    url: "/app-url/relative-url",
    type: "GET", //Or "DELETE" for http delete calls
    dataType: 'json',    
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

jQuery Ajax HTTP POST or PUT Method

$.ajax({
    url: "/app-url/relative-url",
    type: "POST", //Use "PUT" for HTTP PUT methods
    dataType: 'json',   
    data: {
        key : "value",
    }
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

Synchronous vs. Asynchronous Communication

By default, all ajax requests sent through jQuery are async only. If you want to make sync calls (which is not recommended at all because it can cause the browser to freeze, which will create some very unhappy users) the use “async : false” parameter in function call as below:

$.ajax({
    url: "/app-url/relative-url",
    type: "POST", 
    async: false,
    dataType: 'json',    
    data: {
        key : "value",
    }
})
.done (function(data, textStatus, jqXHR) { 
	alert("Success: " + response); 
})
.fail (function(jqXHR, textStatus, errorThrown) { 
	alert("Error"); 
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
	alert("complete"); 
});

In jQuery 1.8 and later, “async : false” option is deprecated.

Global Event Handlers

Apart from above 3 methods, i.e. done(), fail() or always(), jQuery has a set of global AJAX functions which you can use to listen for AJAX events across all AJAX requests sent via jQuery. Let’s walk through them:

$.ajaxSend()

The callback function registered with the ajaxSend() function is always called just before an AJAX request is sent via jQuery.

$(document).ajaxSend(function() {
    console.log("called before each send");
});

$.ajaxStart()

Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event.

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the ajaxStart() method will not fire.

$( document ).ajaxStart(function() {
  	$( "#loading" ).show();
});

$.ajaxStop()

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxStop() method will not fire.

$( document ).ajaxStop(function() {
  	$( "#loading" ).hide();
});

$.ajaxSuccess()

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event.

$( document ).ajaxSuccess(function( event, xhr, settings ) {
  	$( "#msg" ).append( "<li>Successful Request!</li>" );
});

$.ajaxError()

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event.

$( document ).ajaxError(function( event, xhr, settings ) {
  	$( "#msg" ).append( "<li>Failed Request!</li>" );
});

$.ajaxComplete()

Whenever an Ajax request completes, jQuery triggers the ajaxComplete event.

$( document ).ajaxComplete(function( event, xhr, settings ) {
  	$( "#msg" ).append( "<li>Request Completed !!</li>" );
});

$.ajaxSetup() to Globalize Parameters

Do you feel that passing a common set of parameters to all ajax requests is boring, you can use $.ajaxSetup() function to register it once and reuse them in all ajax calls. The $.ajaxSetup() function can be used to set options to be used for all AJAX calls, including those performed via $.ajax(), $.load(), $.get() etc.

You can set all the options in $.ajaxSetup() which can set to a $.ajax() call. e.g.

$.ajaxSetup({
    type : "POST"
});

Above function will make all jQuery ajax requests from application to be HTTP POST methods by default. So anytime, you want to send a HTTP GET method, you must set it explicitly in that particular $.ajax() call like below:

$.ajax({
    url  : "/app-url/relative-url",
    type : "GET"
});

$.ajaxPrefilter() to filter Ajax Requests

If you have been in server-side web-development then you will acknowledge that filters are a great way to achieve certain objectives such as input values sanitation etc. Now jQuery provides this functionality in client-side as well using ajaxPrefilter event. Using this function you can filter all AJAX calls before they are sent to the server.

All Ajax options/parameters passed to the $.ajax() function can be changed (“filtered”) in $.ajaxPrefilter() before the request is sent. e.g. if you want that all HTTP requests sent to URLs ending with “/add” must be HTTP POST calls then you can apply the logic here.

$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if(options.url.indexOf("/add") != -1) 
    {
        options.type = "POST";
    }
});

Here parameters are:

  • options – are the request options
  • originalOptions – are the options as provided to the $.ajax() method, unmodified and, thus, without defaults from ajaxSettings
  • jqXHR – is the jqXHR object of the request

Other Ajax Powered Functions in jQuery

Let’s go through other useful functions provided by the jQuery library using ajax internally, and can be used directly.

$.get() and $.post() Functions

jQuery has these functions which can be used to send simplified HTTP GET and HTTP POST requests. Here is an example showing how to use jQuery’s $.get() function:

var parameters = { p1 : "val1", p2 : "val2"};
$.get( "/app/url", parameters )
.done(function(data) {
    $("#label").html(data);
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

Similarily you can use $.post() function to make HTTP POST request.

var parameters = { p1 : "val1", p2 : "val2"};
$.post( "/app/url", parameters )
.done(function(data) {
    $("#label").html(data);
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

$.load() Function

jQuery load() function loads some HTML via AJAX and inserts it into the selected element. It’ a simple HTTP GET method in the background which fetches some HTML from server and insert it into element’s DOM.

$("#loadTarget").load("html-response.html");

You can also insert just only a part of the HTML loaded. If you append a space + jQuery selector string after the url then load() will only inserted the part of the loaded HTML matching the selector.

$("#loadTarget").load("html-response.html #someDiv");

In above example, ajax call will load HTML response from URL html-response.html and then it will execute jQuery ID selector of response for id=someDiv and then it will insert the result HTML into innerHTML of loadTarget.

If the loaded HTML contains any JavaScript it will get executed when the HTML is inserted into the target HTML element. However, if you load a fragment (URL + jQuery selector) then any JavaScript found in the loaded file is removed before the HTML is inserted.

$.getScript() Function

The $.getScript() function in jQuery loads a JavaScript file and executes it. This function uses jQuery’s underlying AJAX functions so the $.getScript() function cannot load scripts from other domains due to cross-domain restrictions. e.g.

$.getScript("js/myscript.js");

That’s all about working with ajax calls using jQuery. Feel free to drop your comments and suggestions in the below comments section.

Happy Learning !!

Понравилась статья? Поделить с друзьями:
  • Factory data reset ошибка
  • Factorio ошибка скачивания списка модов
  • Factorio ошибка загрузки модов
  • Factorio ошибка 520
  • Factorio как изменить разрешение экрана