Description: Perform an asynchronous HTTP (Ajax) request.
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:
1 2 3 4 5 6 7 8 9 10 11 |
|
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 todeferred.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 todeferred.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 todeferred.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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
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/orresponseText
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:
-
beforeSend
callback option is invoked; it receives thejqXHR
object and thesettings
object as parameters. -
error
callback option is invoked, if the request fails. It receives thejqXHR
, 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». -
dataFilter
callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value ofdataType
, and must return the (possibly altered) data to pass on tosuccess
. -
success
callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and thejqXHR
object. -
Promise callbacks —
.done()
,.fail()
,.always()
, and.then()
— are invoked, in the order they are registered. -
complete
callback option fires, when the request finishes, whether in failure or success. It receives thejqXHR
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.
The data
option can contain either a query string of the form key1=value1&key2=value2
, or an object of the form {key1: 'value1', key2: 'value2'}
. If the latter form is used, the data is converted into a query string using jQuery.param()
before it is sent. This processing can be circumvented by setting processData
to false
. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType
option from application/x-www-form-urlencoded
to a more appropriate MIME type.
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 <script>
tag (that is, a type of script
or jsonp
). This is useful if the script and host page have differing character sets.
The first letter in Ajax stands for «asynchronous,» meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async
option to $.ajax()
defaults to true
, indicating that code execution can continue after the request is made. Setting this option to false
(and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.
The $.ajax()
function returns the XMLHttpRequest
object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr
option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort()
on the object will halt the request before it completes.
Extending Ajax
As of jQuery 1.5, jQuery’s Ajax implementation includes prefilters, transports, and converters that allow you to extend Ajax with a great deal of flexibility.
Using Converters
$.ajax()
converters support mapping data types to other data types. If, however, you want to map a custom data type to a known type (e.g json
), you must add a correspondence between the response Content-Type and the actual data type using the contents
option:
1 2 3 4 5 6 7 8 9 10 11 |
|
This extra object is necessary because the response Content-Types and data types never have a strict one-to-one correspondence (hence the regular expression).
To convert from a supported type (e.g text
, json
) to a custom data type and back again, use another pass-through converter:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The above now allows passing from text
to mycustomtype
and then mycustomtype
to json
.
Examples:
Save some data to the server and notify the user once it’s complete.
1 2 3 4 5 6 7 8 |
|
Retrieve the latest version of an HTML page.
1 2 3 4 5 6 7 |
|
Send an xml document as data to the server. By setting the processData
option to false
, the automatic conversion of data to strings is prevented.
1 2 3 4 5 6 7 8 |
|
Send an id as data to the server, save some data to the server, and notify the user once it’s complete. If the request fails, alert the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Load and execute a JavaScript file.
I have a simple web application.
I’ve created the server REST API so it will return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.).
So, for example if a client send a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"}
.
In jQuery I’m using the «ajax» function to create a POST request. When the server returns something different from HTTP code 200 (OK), jQuery defines it as «error».
The error handler can get 3 parameters: jqXHR, textStatus, errorThrown.
Ho can I get the JSON object that sent by the server in error case?
Edit:
1) Here is my JS code:
function register (userName, password) {
var postData = {};
postData["userName"] = userName;
postData["password"] = password;
$.ajax ({
dataType: "json",
type: "POST",
url: "<server>/rest/register",
data: postData,
success: function(data) {
showResultSucceed(data);
hideWaitingDone();
},
error: function (jqXHR, textStatus, errorThrown) {
showResultFailed(jqXHR.responseText);
hideWaitingFail();
}
})
}
2) When looking at Firebug console, it seems like the response is empty.
When invoking the same request by using REST testing tool, I get a response with JSON object it it.
What am I doing wrong?
Описание: Выполняет асинхронный 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 |
|
Объект 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 |
|
Ссылка 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()
следующие:
-
beforeSend
вызывается всегда; принимаетjqXHR
объект и объектsettings
как параметры. -
error
вызывается, если запрос выполняется с ошибкой. Принимает объектjqXHR
, строку со статусом ошибки и объект исключения если применимо. Некоторые встроенные ошибки обеспечивают строку качестве объекта исключения: «abort», «timeout», «No Transport». -
dataFilter
вызывается немедленно при успешном получении данных ответа. Принимает в качестве параметров возвращенные данные и знчение параметраdataType
и должен вернуть (возможно измененные данные) для передачи далее в обработчикsuccess
. -
success
вызывается если запрос выполнен успешно. Принимает данные ответа, строку содержащую код успеха и объектjqXHR
. -
Promise обработчик —
.done()
,.fail()
,.always()
и.then()
— выполняются, в том порядке в котором зарегистрированы. -
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 |
|
Этот дополнительный объект необходим, потому что Content-Types
ответа и типы данных никогда не имеют однозначного соответствия между собой (отсюда и регулярное выражение).
Для преобразования из поддерживаемого типа (например text
или json
) в пользовательский тип данных и обратно, используйте другой сквозной преобразователь:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Пример выше позволяет перейти из text
в mycustomtype
и затем из mycustomtype
в json
.
Время прочтения
13 мин
Просмотры 37K
Всем привет в новой записи мы с вами разберём основные функции для Ajax запросов, которые позволяют передавать информацию с сайта в PHP скрипт без перезагрузки страницы.
Для работы Ajax запросов вам нужно подключить jQuery к вашему проекту. Ссылку на jQuery вы можете найти здесь.
Данный взяты с моего сайта Prog-Time.
Стандартная отправка данных через Ajax.
$.ajax({
url: '/index.php', /* Куда отправить запрос */
method: 'get', /* Метод запроса (post или get) */
dataType: 'html', /* Тип данных в ответе (xml, json, script, html). */
data: {text: 'Текст'}, /* Данные передаваемые в массиве */
success: function(data){ /* функция которая будет выполнена после успешного запроса. */
alert(data); /* В переменной data содержится ответ от index.php. */
}
});
Отправка POST запроса через Ajax
Для отправки POST запроса используем подобный код, меняем только параметр method
$.ajax({
url: '/index.php',
method: 'post',
dataType: 'html',
data: {text: 'Текст'},
success: function(data){
alert(data);
}
});
Отправка JSON данных через Ajax
Для отправки JSON данный через AJAX можно использовать только методом GET.
$.ajax({
url: '/json.php',
method: 'get',
dataType: 'json',
success: function(data){
alert(data.text); /* выведет "Текст" */
alert(data.error); /* выведет "Ошибка" */
}
});
Запланировать выполнение JS скрипта
После выполнения данного запроса, скрипт указанный в параметре url сразу будет выполнен.
$.ajax({
method: 'get',
url: '/script.js',
dataType: "script"
});
Сокращённые виды функций для Ajax запросов
$.post('/index.php', {text: 'Текст'}, function(data){
alert(data);
});
$.get('/index.php', {text: 'Текст'}, function(data){
alert(data);
});
$.getJSON('/json.php', function(data) {
alert(data.text);
alert(data.error);
});
Сокращённая версия запроса на выполнение JS скрипта
$.getScript('/script.js');
Обработка ошибок связанных с AJAX запросом
$.ajax({
url: '/index.php',
method: 'get',
dataType: 'json',
success: function(data){
console.dir(data);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect. Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found (404).');
} else if (jqXHR.status == 500) {
alert('Internal Server Error (500).');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error. ' + jqXHR.responseText);
}
}
});
7 Основные параметры для работы с AJAX функциями
Справочные данные взяты с сайта – https://basicweb.ru/jquery/jquery_method_ajax.php
Все параметры для отправки AJAX запросов
-
async (по умолчанию: true).Тип: Boolean.По умолчанию, все запросы отправляются асинхронно и не задерживают работу других JS скриптов (это значение true), для того чтобы ждать пока выполниться Ajax запрос – поставьте значение false.Обратите внимание, что кроссдоменные запросы и элемент, параметр dataType которого имеет значение “jsonp” не поддерживают запросы в синхронном режиме. Учтите, что используя синхронные запросы вы можете временно заблокировать браузер отключив какие-либо действия пока запрос будет активен.
-
beforeSendФункция обратного вызова, которая будет вызвана перед осуществлением AJAX запроса. Функция позволяет изменить объект jqXHR (в jQuery 1.4.х объект XMLHTTPRequest) до его отправки. Объект jqXHR это надстройка расширяющая объект XMLHttpRequest, объект содержит множество свойств и методов, которые позволяет получить более полную информацию об ответе сервера, а так же объект содержит Promise методы. Если функция beforeSend возвращает false, то AJAX запрос будет отменен. Начиная с версии jQuery 1.5 функция beforeSend будет вызываться независимо от типа запроса.
-
cache (по умолчанию: true, для dataType “script” и “jsonp” false).Тип: Boolean.Если задано значение false, то это заставит запрашиваемые страницы не кэшироваться браузером. Обратите внимание, что значение false будет правильно работать только с HEAD и GET запросами.
-
complete.Тип: Function( jqXHR jqXHR, String textStatus ).Функция, которая вызывается, когда запрос заканчивается (функция выполняется после AJAX событий “success” или “error”). В функцию передаются два параметра: jqXHR (в jQuery 1.4.х объект XMLHTTPRequest) и строка соответствующая статусу запроса (“success”, “notmodified”, “nocontent”, “error”, “timeout”, “abort”, или “parsererror”). Начиная с версии jQuery 1.5 параметр complete может принимать массив из функций, которые будут вызываться по очереди.
-
contents.Тип: PlainObject.Объект состоящий из пар строка/регулярное выражение, определяющих, как jQuery будет обрабатывать (парсить) ответ в зависимости от типа содержимого. Добавлен в версии jQuery 1.5.
-
contentType (по умолчанию: “application/x-www-form-urlencoded; charset=UTF-8”).Тип: Boolean, или String.Определяет тип содержимого, которое указывается в запросе при передаче данных на сервер. С версии с jQuery 1.6 допускается указать значение false, в этом случае jQuery не передает в заголовке поле Content-Type совсем.
-
context.Тип: PlainObject.При выполнении AJAX функций обратного вызова контекстом их выполнения является объект window. Параметр context позволяет настроить контекст исполнения функции таким образом, что $( this ) будет ссылаться на определенный DOM элемент, или объект.
$.ajax({
url: "test.html", // адрес, на который будет отправлен запрос
context: $( ".myClass" ), // новый контекст исполнения функции
success: function(){ // если запрос успешен вызываем функцию
$( this ).html( "Всё ок" ); // добавляем текст в элемент с классом .myClass
}
});
-
crossDomain (по умолчанию: false для запросов внутри того же домена, true для кроссдоменных запросов).Тип: Boolean.Если вы хотите сделать кроссдоменный запрос находясь на том же домене (например jsonp-запрос), то установите этот параметр в true. Это позволит, к примеру, сделать перенаправление запроса на другой домен с вашего сервера. Добавлен в версии jQuery 1.5.
-
data.Тип: PlainObject, или String, или Array.Данные, которые будут отправлены на сервер. Если они не является строкой, то преобразуются в строку запроса. Для GET запросов строка будет добавлена к URL. Для того, чтобы предотвратить автоматическую обработку вы можете воспользоваться параметром processData со значением false. Если данные передаются в составе объекта, то он должен состоять из пар ключ/значение. Если значение является массивом, то jQuery сериализует несколько значений с одним и тем же ключом (в зависимости от значения параметра traditional, который позволяет задействовать традиционный тип сериализации основанный на методе $.param).
-
dataFilter.Тип: Function( String data, String type ) => Anything.Функция вызывается после успешного выполнения AJAX запроса и позволяет обработать “сырые” данные, полученные из ответа сервера. Возврат данных должен происходить сразу после их обработки. Функция принимает два аргумента: data – данные полученные от сервера в виде строки и type – тип этих данных (значение параметра dataType).
-
dataType (по умолчанию: xml, json, script, или html ).Тип: String.Определяет тип данных, который вы ожидаете получить от сервера. Если тип данных не указан, то jQuery будет пытаться определить его на основе типа MIME из ответа (XML тип MIME приведет к получению XML, с версии jQuery 1.4 json будет давать объект JavaScript, script будет выполнять скрипт, а все остальное будет возвращено в виде строки).Основные типы (результат передается в качестве первого аргумента в функцию обратного вызова success):
-
“xml” – возвращает XML документ, который может быть обработан с помощью jQuery.
-
“html” – возвращает HTML как обычный текст, теги <script> будут обработаны и выполнены после вставки в объектную модель документа (DOM).
-
“script” – расценивает ответ как JavaScript и возвращает его как обычный текст. Отключает кэширование с помощью добавления параметра к строке запроса _=[TIMESTAMP], даже если парамета cache имеет значение true. Это превратит метод POST в GET для кроссдоменных запросов.
-
“json” – расценивает ответ как JSON и возвращает объект JavaScript. Кроссдоменные “json” запросы преобразуются в “jsonp”, если в параметрах запроса не указано jsonp: false. Данные JSON парсятся в строгом порядке и должны соответствовать общепринятому формату, любой некорректный JSON отвергается и выдается ошибка. С версии jQuery 1.9, пустой ответ не принимается, сервер должен вернуть в качестве ответа NULL, или {}.
-
“jsonp” – загружает данные в формате JSON, используя при этом формат загрузки JSONP. Добавляет дополнительный параметр “?callback=?” в конец URL адреса для указания имени функции обработчика. Отключает кэширование путем добавления параметра _=[TIMESTAMP] к URL адресу,даже если парамета cache имеет значение true.
-
“text” – обычная текстовая строка.
-
несколько значений – значения разделяются пробелом. Начиная с версии 1.5, jQuery может преобразовать тип данных, который получен в Content-Type заголовка, в тип данных, который вам требуется. Например, если вы хотите, чтобы текстовый ответ был расценен как XML, используйте “text XML” для этого типа данных. Вы также можете сделать JSONP запрос, получить его в виде текста и интерпретировать его в формате XML: “jsonp text XML”. Следующая строка позволит сделать тоже самое: “jsonp XML”, jQuery будет пытаться конвертировать из JSONP в XML, после неудачной попытки попытается преобразовать JSONP в текст, а затем из текста уже в XML.
-
-
error.Тип: Function( jqXHR jqXHR, String textStatus, String errorThrown ).Функция обратного вызова, которая вызывается если AJAX запрос не был выполнен. Функция получает три аргумента:
-
jqXHR – объект jqXHR (в jQuery 1.4.х, объект XMLHttpRequest).
-
textStatus – строка, описывающую тип ошибки, которая произошла. Возможные значения (кроме null) не “timeout”, “error”, “abort” и “parsererror”.
-
errorThrown – дополнительный объект исключения, если произошло. При возникновении ошибки HTTP аргумент получает текстовую часть состояния, например, “Not Found”, или “Internal Server Error”.Начиная с версии jQuery 1.5 допускается передавать в качестве значения параметра массив функций, при этом каждая функция будет вызвана в свою очедерь. Обратите внимание, что этот обработчик не вызывается для кроссдоменных скриптов и запросов JSONP.
-
-
global (по умолчанию: true).Тип: Boolean.Логический параметр, который определяет допускается ли вызвать глобальные обработчики событий AJAX для этого запроса. Значением по умолчанию является true. Если Вам необходимо предотвратить вызов глобальных обработчиков событий, таких как .ajaxStart(), или .ajaxStop(), то используйте значение false.
-
headers (по умолчанию: { }).Тип: PlainObject.Объект, который содержит пары ключ/значение дополнительных заголовков запроса, предназначенные для отправки вместе с запросом с использованием объекта XMLHttpRequest. Обращаю Ваше внимание, что заголовок X-Requested-With: XMLHttpRequest добавляется всегда, но значение XMLHttpRequest по умоланию допускается изменить с использованием этого параметра. Значения headers также могут быть переопределены параметром beforeSend. Добавлен в версии jQuery 1.5.
-
ifModified (по умолчанию: false).Тип: Boolean.По умолчанию значение false, игнорирует поля заголовка HTTP запроса, а при значении true AJAX запрос переводится в статус успешно (success), только в том случае, если ответ от сервера изменился с момента последнего запроса. Проверка производится путем проверки поля заголовка Last-Modified. Начиная с версии jQuery 1.4, помимо заголовка Last-Modified производится проверка и “etag” (entity tag) – это закрытый идентификатор, присвоенный веб-сервером на определенную версию ресурса, найденного на URL. Если содержание ресурса для этого адреса меняется на новое, назначается и новый etag.
-
isLocal (по умолчанию: зависит от текущего местоположения).Тип: Boolean.Используйте значение true для определения текущего окружения как “локального” (например, file:///url), даже если jQuery не распознает его таким по умоланию. Следующие протоколы в настоящее время признаются как локальные: file, *-extension и widget. Если Вам необходимо изменить параметр isLocal, то рекомендуется сделать это один раз при помощи функции $.ajaxSetup(). Добавлен в версии jQuery 1.5.1.
-
jsonpТип: Boolean, или String.Переопределяет имя функции обратного вызова в JSONP запросе. Это значение будет использоваться вместо “callback“ (“http://domain.ru/test.php?callback=?”) в составе части строки запроса в URL адресе. Например, значение {jsonp: “onLoad“} передастся на сервер в виде следующей строки запроса “http://domain/test.php?onLoad=?”.Начиная с версии jQuery 1.5 при установке значения параметра jsonp в значение false предотвращает добавление строки “?callback” к URL адресу, или попытки использовать “=?” для преобразования ответа. В этом случае Вы дополнительно должны указать значение параметра jsonpCallback. По соображениям безопасности, если Вы не доверяете цели ваших AJAX запросов, то рекомендуется установить значение параметра jsonp в значение false.
{
jsonp: false,
jsonpCallback: "callbackName"
}
-
jsonpCallback.Тип: String, или Function.Задает имя функции обратного вызова для JSONP запроса. Это значение будет использоваться вместо случайного имени, которое автоматически генерируется и присваивается библиотекой jQuery. Рекомендуется, чтобы jQuery самостоятелно генерировало уникальное имя, это позволит легче управлять запросами и обрабатывать возможные ошибки. В некоторых случаях установка собственного имени функции позволит улучшить браузерное кеширование GET запросов.Начиная с версии jQuery 1.5, вы можете в качестве значения параметра jsonpCallback указать функцию. В этом случае, в значение параметра jsonpCallback должно быть установлено возвращаемое значение этой функцией.
-
method (по умолчанию: “GET”).Тип: String.Метод HTTP, используемый для запроса (например, “POST”, “GET”, “PUT”). Добавлен в версии jQuery 1.9.0.
-
mimeType.Тип: String.MIME тип, который переопределяет MIME тип, указанынй в объекте XHR по умолчанию. Добавлен в версии jQuery 1.5.1.
-
password.Тип: String.Пароль, который будет использован с XMLHttpRequest в ответе на запрос проверки подлинности доступа HTTP.
-
processData (по умолчанию: true).Тип: Boolean.По умолчанию данные, передаваемые в параметр data в качестве объекта будут обработаны и преобразованы в строку запроса, подходящую для типа данных по умолчанию “application/x-www-form-urlencoded”. Если Вам необходимо отправить DOMDocument, или другие не обработанные данные, то установите значение этого параметра в false.
-
scriptCharset.Тип: String.Устанавливает атрибут charset (кодировка символов) на HTML тег <script>, используемый в запросе. Используется, когда кодировка на странице отличается от кодировки удаленного скрипта. Обратите внимание, что параметр scriptCharset применяется только в кроссдоменных запросах с параметром type со значением “GET” (по умолчанию) и параметром dataType со значением “jsonp”, или “script”.
-
statusCode (по умолчанию: { }).Тип: PlainObject.Объект числовых кодов HTTP и функции, которые будут вызываться, когда код ответа сервера имеет соотвествующее значение (определенный код HTTP). Например, следующая функция будет вызвана, если от сервера получен код ответа 404, или “Not found” (стандартный код ответа HTTP о том, что клиент был в состоянии общаться с сервером, но сервер не может найти данные согласно запросу.)
$.ajax({
statusCode: {
404: function(){ // выполнить функцию если код ответа HTTP 404
alert( "страница не найдена" );
},
403: function(){ // выполнить функцию если код ответа HTTP 403
alert( "доступ запрещен" );
}
}
});
-
success.Тип: Function( Anything data, String textStatus, jqXHR jqXHR ).Функция обратного вызова, которая вызывается если AJAX запрос выполнится успешно. Функции передаются три аргумента:
-
data – данные возвращенные с сервера. Данные форматируюся в соответствии с параметрами dataType, или dataFilter, если они указаны
-
textStatus – строка описывающая статус запроса.
-
jqXHR – объект jqXHR (до версии jQuery 1.4.x объект XMLHttpRequest).Начиная с версии jQuery 1.5 допускается передавать в качестве значения параметра массив функций, при этом каждая функция будет вызвана в свою очедерь.
-
-
timeout.Тип: Number.Устанавливает в миллисекундах таймаут для запроса. Значение 0 означает, что таймаут не установлен. Обращаю Ваше внимание, что этот параметр переопределяет значение таймаута, установленного с помощью функции $.ajaxSetup(). Таймаут ожидания начинается в момент вызова метода $.ajax().
-
traditional.Тип: Boolean.Если вы планируете использовать традиционные параметры сериализации (подходит для использования в строке URL запроса или запроса AJAX), то установите значение этого параметра в true.
-
type (по умолчанию: “GET”).Тип: String.Псевдоним (алиас) для параметра method. Вы должны использовать type, если вы используете версии jQuery до 1.9.0.
-
url (по умолчанию: текущая страница).Тип: String.Строка, содержащая URL адрес, на который отправляется запрос.
-
username.Тип: String.Имя пользователя, которое будет использовано с XMLHttpRequest в ответе на запрос проверки подлинности доступа HTTP.
-
xhr (по умолчанию: ActiveXObject, когда доступен (Internet Explorer), в других случаях XMLHttpRequest.Тип: Function().Обратный вызов для создания объекта XMLHttpRequest. С помощью этого параметра Вы можете переопределить объект XMLHttpRequest, чтобы обеспечить свою собственную реализацию.
-
xhrFields.Тип: PlainObject.Объект, содержащий пары имя_поля: значение_поля, которые будут установлены на объект XHR. Например, вы можете определить, должны ли создаваться кроссдоменные запросы с использованием таких идентификационных данных как cookie, авторизационные заголовки или TLS сертификаты
$.ajax({
url: "cross_domain_url", // адрес, на который будет отправлен запрос
xhrFields: {
withCredentials: true // поддерживается в jQuery 1.5.1 +
}
});
Форма с отправкой файлов методом AJAX
Создаём форму с 2 текстовыми полями name и phone, и одним полем для передачи файла (fileImage)
HTML
<form id="feedBack" method="post" onsubmit="return false">
<input type="text" name="name" placeholder="Имя">
<input type="tel" name="phone" placeholder="Телефон">
<input type="file" name="fileImage" accept=".jpg, .jpeg, .png" multiple="multiple">
<input type="submit" value="Отправить">
</form>
JQUERY
/* запускаем скрипт после полной загрузки документа /
$("document").ready(function() {
/ вешаем событие на ранее созданную форму /
$("#feedBack").on("submit", function() {
/ создаём объект с данными из полей /
let formData = new FormData(feedBack)
/ добавляем дополнительные данные для отправки */
formData.append("url_query", "prog-time");
/* записываем в переменную данные картинок из формы */
let allfiles = $(this).find('input[name="fileImage"]');
/* пробегаем покартинкам и записываем их в массив для отправки */
for(var i = 0; i < allfiles[0].files.length; i++){
formData.append("file_"+i, allfiles[0].files[i]);
}
/* отправляем AJAX запрос */
$.ajax({
type: "POST",
url: '/query.php',
contentType: false,
processData: false,
data: formData,
success: function(data){
console.log(data)
},
});
})
})
11 PHP
/* ... прописываем необходимые проверки и обработки данных */
/* сохраняем картинки на сервере */
foreach(image["name"], $image["tmp_name"]);
}
На этом всё!
Прокачивайте свои навыки на нашем канале.
AJAX or Asynchronous Javascript and XML allows for content retrieval and display without reloading the web page. The concept is to send that the client sends the request and while waiting it can do other tasks but once the response returns we can do whatever we want with the it, well, according to the pre-set instructions that we set before dubbed callbacks.
Things to know before diving into AJAX
Web APIs
API is an acronym for Application Programming Interface. We’ll be using APIs to interact with various data sources.
Read more about web APIs:
- Introduction to web APIs.
- What is an API? In English, please.
Same Origin Policy
The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin.
Note: Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.
Read more about same-origin policy:
- MDN — Same-origin policy
- TechTarget — Same Origin Policy (SOP)
CORS
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) than its own origin.
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser.
Read more about CORS:
- MDN — Cross-Origin Resource Sharing (CORS)
- Code Academy — What is CORS?
AJAX with XHR
An XMLHttpRequest
object (commonly abbreviated as XHR or xhr) is provided by the javascript environment and is used to make AJAX requests. The «issue» with XHR is that you have to manually do a lot of the steps to get the request set up and finally sent off, so when the response comes back there are already instructions to handle the data.
Note: The name XMLHttpRequest is historical and has no bearing on its functionality.
To create an XMLHttpRequest
object, we use the XMLHttpRequest
constructor function.
const asyncRequestObject = new XMLHttpRequest();
The ‘open()’ method
The XHR method open()
initializes a newly-created request, or re-initializes an existing one. open()
takes a number of parameters, but the most important are its first two: the HTTP method (GET
, POST
, …) and URL to send the request to.
Note: Calling this method for an already active request (one for which open() has already been called) is the equivalent of calling abort()
.
If we want to asynchronously request the homepage from the popular high-res image site, Unsplash, we’d use a GET
request and provide the URL:
asyncRequestObject.open('GET', 'https://unsplash.com');
The XHR’s open()
method does not actually send the request. It sets the stage and gives the object the info it will need when the request is actually sent.
XHR can perform the operation synchronously by setting the 3rd parameter to false
, but it is not recommeneded to do so.
const mySyncRequest = new XMLHttpRequest(); myAsyncRequest.open('GET', 'https://udacity.com/', false);
The ‘send()’ method
The XHR method send()
sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://unsplash.com'); xhr.send();
Running the above code will do nothing other than sending the request. To watch for our response we need to set some handlers for when the response succeeds and when an error occurs, and we do that through the onload
and onerror
properties.
Handling success
function handleSuccess () { // in the function, the `this` value is the XHR object // this.responseText holds the response from the server console.log( this.responseText ); // the HTML of https://unsplash.com/ } xhr.onload = handleSuccess;
Note: Not setting the onload
property will render the request useless.
Handling errors
function handleError () { // in the function, the `this` value is the XHR object console.log( 'An error occurred 😞' ); } xhr.onerror = handleError;
Note: If by any chance an error occurs and you haven’t set the ònerror
property and handled errors, your code will fail silently.
Putting it all together
function handleSuccess () { console.log( this.responseText ); // the HTML of https://unsplash.com/ } function handleError () { console.log( 'An error occurred uD83DuDE1E' ); } const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://unsplash.com'); xhr.onload = handleSuccess; xhr.onerror = handleError; xhr.send();
If the data we are requesting is in JSON format we need to convert that JSON response (this.responseText
) into a javascript object. That can be done with JSON.parse();
, and our code should now look like this:
function handleSuccess () { const data = JSON.parse( this.responseText ); // convert data from JSON to a JavaScript object console.log( data ); } xhr.onload = handleSuccess;
XMLHttpRequest
object has other methods and properties that you can check in the XMLHttpRequest MDN documentation
Recap
To Send An Async Request
- create an XHR object with the
XMLHttpRequest
constructor function - use the
.open()
method — set the HTTP method and the URL of the resource to be fetched - set the
.onload
property — set this to a function that will run upon a successful fetch - set the
.onerror
property — set this to a function that will run when an error occurs - use the
.send()
method — send the request
To Use The Response
- use the
.responseText
property — holds the text of the async request’s response - use the
JSON.parse()
method (when requesting JSON data) — converts the JSON data to a javascript object
Note: The .responseText
property is accessible through the this
keyword, so make sure to use function declaration when setting the .onload
property.
AJAX with jQuery
jQuery is an incredibly popular JavaScript library that provides a lot of functionality right out of the box. What is important to us here is jQuery’s ajax()
method that really eases up the handling of asynchronous requests.
The ‘ajax()’ method
You can use the ajax()
method by either providing a requestUrl
and a configuration object, just like so:
$.ajax(requestUrl, settings);
or just the settings
object, which is «cleaner»
Making an AJAX call
Unlike XMLHttpRequest where we had to «open» the request, then «send» it, jQuery does all that for us. A simple AJAX call with jQuery’s ajax()
looks like this:
$.ajax({ url: 'https://swapi.co/api/people/1/' });
We are not specifying the HTTP GET
method here because it defaults to GET
, but we can set the HTTP method througn the configuration object like so:
$.ajax({ url: '<url_to_post_data>', method: '<method>', // ... });
Note: There are other options that you can set in the jquery settings object, you can check that in the offcial jQuery’s ajax docs
Handling success
There are two ways to handle the returned data when the request is successful. The first is by setting the success
property on the settings object, and the second/cleaner way is by chaining the .done()
method on to .ajax()
which works like ES2015 promises.
$.ajax({ url: 'https://swapi.co/api/people/1/' }).done(function(data) { debugger; // work with the returned response });
Note: When the received data is in JSON format jQuery automatically converts it to javascript object, so there is no need to use JSON.parse()
method!
Handling errors
Just like handling success, handling errors can be done in two ways, either by setting the error
property on the settings object or by chaining the .fail()
method to .ajax()
, we’ll be working with the latter.
$.ajax({ url: 'https://swapi.co/api/people/1/' }) .done(function(data) { debugger; // work with the returned response }) .fail(/* handling errors*/function(error) { // Do something with error });
Other jQuery async methods
jQuery comes with other async functions to make asynchronous calls that work as shortcuts to the .ajax()
method:
.get()
.getJSON()
.getScript()
.post()
.load()
Note: The jQuery website recommends using .ajax()
method over these convenience methods.
Wrap up
Using jQuery’s ajax()
method to handle async requests can save us lots of setup, it
- creates a new XHR object each time it’s called
- sets all of the XHR properties and methods
- sends the XHR request
But this comes with a price, which is including the whole jQuery library and that is some expensive network call.
AJAX with Fetch
Fetch is a new API that was built to make requesting resources (primarily across a network) a whole lot easier. One thing that makes the new Fetch API a lot nicer than the old XHR way of doing things is that Fetch is promise-based!
Browser support and fallback
Fetch API is fairly new, so it’s not widely supported in older browser, that is why you need to check for browser support of the fetch API.
In case it’s not supported in your targeted browsers make sure to use this fetch polyfill.
Making a fetch request
A simple ‘GET’ request using the Fetch API is as simple as so
fetch('https://swapi.co/api/people/1/')
Specifying HTTP method (append
, has
, get
, set
, or delete
), headers, mode (cors
, no-cors
, or same-origin
) and other settings is done through the configuration object that is passed to the fetch()
method as second argument.
So, sending a request with the HTTP POST
method and Authorization
headers using the Fetch API would look like this:
fetch('<request_url>', { method: 'POST', headers: { Authorization: '<some_auth_string>' }, //... });
Headers can also be set with a Headers object, like so:
const reqHeaders = new Headers(); reqHeaders.append('Authorization', '<some_auth_string>'); fetch('<request_url>', { headers: reqHeaders, //... });
Handling the response
Fetch is Promise-based. This means that when we fire of the Fetch request, it will automatically return a Promise that we can use to listen for the response. Read more about javascript promises.
Since fetch()
method returns a Promise that resolves with the Response
object, then all we have to do is chain a .then()
on that Promise.
fetch(`<request_url>`, { // ... }).then((response) => { debugger; // work with the returned 'response' });
The Response
object doesn’t have the data, it only has information about the response itself (type
, url
, status
, headers
, ok
, …). To actually get the data, we need to get the «body» of the response.
Handling JSON Responses
If the data we are requesting is JSON, then we should call the .json()
method of the Response
object that returns a Promise that resolves with data as javascript object.
fetch(`<request_url>`, { // ... }) .then((response) => response.json()) .then((data) => { debugger; // work with the returned JSON data });
Handling Text/HTML Responses
If the response data is HTML or text, then we should call the .text()
method.
fetch(`<request_url>`, { // ... }) .then((response) => response.text()) .then((data) => { debugger; // work with the returned HTML string });
Handling Blob Responses
To load an image with fetch we use the blob()
method that resolves with a Blob
. A Blob
object represents a file-like object of immutable, raw data.
fetch('<path_or_url_to_img>/cute_cat.jpg') .then( response => response.blob()) .then((imageBlob) => { document.querySelector('img').src = URL.createObjectURL(imageBlob); });
validating the response
Make sure to validate the response, as in check if the response is valid (i.e. 2xx). You can do that by checking if the response.ok
property is true
.
const validateResponse = (response) => { if (!response.ok) { throw Error(response.statusText); } return response; } fetch(`<request_url>`, { // ... }) .then(validateResponse) .then((response) => response.json()) .then((data) => { debugger; // work with the returned JSON data });
Handling Errors
Since the fetch()
returns a Promise
, we can handle errors by chaining a .catch()
method on the tail of the fetch chain.
fetch(`<request_url>`, { // ... }) .then((response) => { // return with the appropriate method json(), text() or blob() }) .then((data) => { // Do something with the data }) .catch((err) => { // Handle the error });
Resources and Usefull links
- MDN — Using XMLHttpRequest
- XMLHttpRequest MDN documentation
- jQuery AJAX documentation
- Fetch Spec
- Fetch API by David Walsh
- MDN — Using Fetch
- Google — PWA — Working with the fetch API
Related
- Pause Your Code With Breakpoints
- JavaScript Debugging Reference
- MDN — Promise
- JavaScript Promises: an Introduction
- JavaScript Promises for Dummies
- Master the JavaScript Interview: What is a Promise?
In this post we will show you how to jQuery ajax error function when Ajax decision passing information to a page that then returns a worth(value).
I have retrieved the self-made decision from the page however I even have coded it so it raises an erreo(bug) within the your call page(example url: "data.php"
). however do we retrieve that error from the jquery? how we get jQuery Ajax Error Handling Function hear is the solution of ajax error function.
this jQuery ajax error function is very basic and easy to use with your ajax call.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data) { // success alert message alert(data); }, error: function (error) { // error alert message alert('error :: ' + eval(error)); } });
jQuery ajax error function using jqXHR
jQuery ajax error function using jqXHR in this function we can get different type ajax error like 404 page error, 500 Internal Server error, Requested JSON parse, Time out error.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data) { // success alert message alert(data); }, error: function (jqXHR, exception) { var error_msg = ''; if (jqXHR.status === 0) { error_msg = 'Not connect.n Verify Network.'; } else if (jqXHR.status == 404) { // 404 page error error_msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { // 500 Internal Server error error_msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { // Requested JSON parse error_msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { // Time out error error_msg = 'Time out error.'; } else if (exception === 'abort') { // request aborte error_msg = 'Ajax request aborted.'; } else { error_msg = 'Uncaught Error.n' + jqXHR.responseText; } // error alert message alert('error :: ' + error_msg); }, });
Parameters for jQuery ajax error function with jqXHR
Parameters for jQuery ajax error function with jqXHR for It actually an error object which is looks like this.
jQuery ajax error function with an validation error
jQuery ajax error function with an validation error :: If we want to inform(get error message) in frontend about an validation error try this method.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data, textStatus, jqXHR) { console.log(data.error); } });
AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.
Полное описание функции AJAX на jquery.com.
1
GET запрос
Запрос идет на index.php с параметром «text
» и значением «Текст
» через метод GET.
По сути это то же самое что перейти в браузере по адресу – http://site.com/index.php?text=Текст
В результате запроса index.php вернет строку «Данные приняты – Текст», которая будет выведена в сообщении alert.
$.ajax({
url: '/index.php', /* Куда пойдет запрос */
method: 'get', /* Метод передачи (post или get) */
dataType: 'html', /* Тип данных в ответе (xml, json, script, html). */
data: {text: 'Текст'}, /* Параметры передаваемые в запросе. */
success: function(data){ /* функция которая будет выполнена после успешного запроса. */
alert(data); /* В переменной data содержится ответ от index.php. */
}
});
JS
Код можно сократить используя функцию $.get
$.get('/index.php', {text: 'Текст'}, function(data){
alert(data);
});
JS
Код файла index.php
echo 'Данные приняты - ' . $_GET['text'];
PHP
GET запросы могут кэшироваться браузером или сервером, чтобы этого избежать нужно добавить в функцию параметр – cache: false
.
$.ajax({
url: '/index.php',
method: 'get',
cache: false
});
JS
2
POST запросы
$.ajax({
url: '/index.php',
method: 'post',
dataType: 'html',
data: {text: 'Текст'},
success: function(data){
alert(data);
}
});
JS
Или сокращенная версия – функция $.post
$.post('/index.php', {text: 'Текст'}, function(data){
alert(data);
});
JS
Код файла index.php
echo 'Данные приняты - ' . $_POST['text'];
PHP
POST запросы ни когда не кэшироваться.
3
Отправка формы через AJAX
При отправке формы применяется функция serialize()
, подробнее на jquery.com.
Она обходит форму и собирает названия и заполненные пользователем значения полей и возвращает в виде массива – {login: 'ЗНАЧЕНИЯ_ПОЛЯ', password: 'ЗНАЧЕНИЯ_ПОЛЯ'}
.
Особенности serialize()
:
- Кнопки формы по которым был клик игнорируются, в результате функции их не будет.
- serialize можно применить только к тегу form и полям формы, т.е.
$('div.form_container').serialize();
– вернет пустой результат.
Пример отправки и обработки формы:
<div class="form_container">
<div id="message"></div>
<form id="form">
<input type="text" name="login">
<input type="text" name="password">
<input type="submit" name="send" value="Отправить">
</form>
</div>
<script>
$("#form").on("submit", function(){
$.ajax({
url: '/handler.php',
method: 'post',
dataType: 'html',
data: $(this).serialize(),
success: function(data){
$('#message').html(data);
}
});
});
</script>
HTML
Код файла handler.php
if (empty($_POST['login'])) {
echo 'Укажите логин';
} elseif (empty($_POST['password'])) {
echo 'Укажите пароль';
} else {
echo 'Авторизация...';
}
PHP
4
Работа с JSON
Идеальный вариант когда нужно работать с массивами данных.
$.ajax({
url: '/json.php',
method: 'get',
dataType: 'json',
success: function(data){
alert(data.text); /* выведет "Текст" */
alert(data.error); /* выведет "Ошибка" */
}
});
JS
Короткая версия
$.getJSON('/json.php', function(data) {
alert(data.text);
alert(data.error);
});
JS
$.getJSON
передает запрос только через GET.
Код файла json.php
header('Content-Type: application/json');
$result = array(
'text' => 'Текст',
'error' => 'Ошибка'
);
echo json_encode($result);
PHP
Возможные проблемы
При работе с JSON может всплыть одна ошибка – после запроса сервер отдал результат, все хорошо, но метод success
не срабатывает. Причина кроется в серверной части (PHP) т.к. перед данными могут появится управляющие символы, например:
Из-за них ответ считается не валидным и считается как ошибочный запрос.
В таких случаях помогает очистка буфера вывода ob_end_clean
(если он используется на сайте).
...
// Очистка буфера
ob_end_clean();
header('Content-Type: application/json');
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit();
PHP
5
Выполнение JS загруженного через AJAX
В JQuery реализована функция подгруздки кода JS через AJAX, после успешного запроса он будет сразу выполнен.
$.ajax({
method: 'get',
url: '/script.js',
dataType: "script"
});
JS
Или
$.getScript('/script.js');
JS
6
Дождаться выполнения AJAX запроса
По умолчанию в JQuery AJAX запросы выполняются асинхронно. Т.е. запрос не задерживает выполнение программы пока ждет результатов, а работает параллельно.
Простой пример:
var text = '';
$.ajax({
url: '/index.php',
method: 'get',
dataType: 'html',
success: function(data){
text = data;
}
});
alert(text); /* Переменная будет пустая. */
JS
Переменная text
будет пустая, а не как ожидается текст который вернул index.php
Чтобы включить синхронный режим нужно добавить параметр async: false
.
Соответственно синхронный запрос будет вешать прогрузку страницы если код выполняется в <head>
страницы.
var text = '';
$.ajax({
url: '/index.php',
method: 'get',
dataType: 'html',
async: false,
success: function(data){
text = data;
}
});
alert(text); /* В переменной будет результат из index.php. */
JS
7
Отправка HTTP заголовков
Через AJAX можно отправить заголовки HEAD, они указываются в параметре headers
.
$.ajax({
url: '/index.php',
method: 'get',
dataType: 'html',
headers: {'Token_value': 123},
success: function(data){
console.dir(data);
}
});
JS
В PHP они будут доступны в массиве $_SERVER
, ключ массива переводится в верхний регистр с приставкой HTTP_
, например:
<?php
echo $_SERVER['HTTP_TOKEN_VALUE']; // 123
PHP
8
Обработка ошибок
Через параметр error
задается callback-функция, которая будет вызвана в случаи если запрашиваемый ресурс отдал 404, 500 или другой код.
$.ajax({
url: '/index.php',
method: 'get',
dataType: 'json',
success: function(data){
console.dir(data);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect. Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found (404).');
} else if (jqXHR.status == 500) {
alert('Internal Server Error (500).');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error. ' + jqXHR.responseText);
}
}
});
JS
Через $.ajaxSetup
можно задать обработчик ошибок для всех AJAX-запросов на сайте.
$.ajaxSetup({
error: function (jqXHR, exception) {
...
}
});
JS
April 16, 2019 by Areg Sarkissian
Introduction
It is critical to have global exception handling for ASP.NET Core applications to respond appropriately to exceptions that are not handled by application logic.
Global exception handling allows us to log all unhandled exceptions in a central location in our application and then provide a user friendly response to the user.
In ASP.NET MVC projects, there are generally two types of content returned to the web browser. There are normal web page requests that require returning HTML content and there are AJAX requests that normally require returning JSON formatted content.
When the browser requests a HTML rendered page and an exception occurs that the application cannot handle, we generally redirect the browser to an HTML error page.
However, when the browser makes an AJAX request that expects a JSON response then we need to return a JSON error response instead of redirecting to a HTML error page.
Given this, in a global exception handler, we need to distinguish between normal web page requests, so that we can return the appropriate error response.
Using HTTP request headers in the Global Exception Handler
The way we can detect if an AJAX request expects a JSON response is by inspecting the HTTP Accept header sent by the request.
The global exception handler in our MVC application can determine whether to send a JSON error response or redirect to a HTML error page based on the value of the Accept header.
If an Accept header exists that contains the value application/json
, then the handler needs to respond with a JSON error response.
Note: Detecting if a request is an AJAX request is not the same as detecting whether the request accepts a JSON response. To detect an AJAX request you can check for a X-Requested-With request header that contains the value
xmlhttprequest
.
Adding a Global exception handler middleware
We can add a Global exception handler middleware that can access the unhandled exception and the request headers from the HTTP request context to decide how to format the exception data for the response.
This middleware will return JSON data for requests that contain the applicationjson
Accept header and otherwise will redirect to an HTML error page.
Also the middleware will serialize and log the exception information.
Below you can see my sample implementation of the global exception handler middleware implemented as an IApplicationBuilder
extension method:
public static class GlobalExceptionHandlerExtension
{
//This method will globally handle logging unhandled execeptions.
//It will respond json response for ajax calls that send the json accept header
//otherwise it will redirect to an error page
public static void UseGlobalExceptionHandler(this IApplicationBuilder app
, ILogger logger
, string errorPagePath
, bool respondWithJsonErrorDetails=false)
{
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
//============================================================
//Log Exception
//============================================================
var exception = context.Features.Get<IExceptionHandlerFeature>().Error;
string errorDetails = $@"{exception.Message}
{Environment.NewLine}
{exception.StackTrace}";
int statusCode = (int)HttpStatusCode.InternalServerError;
context.Response.StatusCode = statusCode;
var problemDetails = new ProblemDetails
{
Title = "Unexpected Error",
Status = statusCode,
Detail = errorDetails,
Instance = Guid.NewGuid().ToString()
};
var json = JsonConvert.SerializeObject(problemDetails);
logger.LogError(json);
//============================================================
//Return response
//============================================================
var matchText="JSON";
bool requiresJsonResponse = context.Request
.GetTypedHeaders()
.Accept
.Any(t => t.Suffix.Value?.ToUpper() == matchText
|| t.SubTypeWithoutSuffix.Value?.ToUpper() == matchText);
if (requiresJsonResponse)
{
context.Response.ContentType = "application/json; charset=utf-8";
if(!respondWithJsonErrorDetails)
json = JsonConvert.SerializeObject(new { Title = "Unexpected Error"
, Status = statusCode});
await context.Response
.WriteAsync(json, Encoding.UTF8);
}
else
{
context.Response.Redirect(errorPagePath);
await Task.CompletedTask;
}
});
});
}
}
ASP.NET Core 2.2 has infrastructure code that makes it easy to parse out the Accept header components and an error data container that can be serialized to JSON and returned as a response.
The handler first logs the error using the supplied logger and then returns the proper response based on the content of the Accept header.
An additional flag is used to limit the JSON data returned in the response.
We can now replace the original app.UseExceptionHandler("/Home/Error")
call in the Startup.Configure(...)
method with our own exception handler middleware:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseGlobalExceptionHandler( _logger
, errorPagePath: "/Home/Error"
, respondWithJsonErrorDetails: true);
//Replaced UseExceptionHandler with UseGlobalExceptionHandler
//app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
The complete source code of the demo app can be found in my Github https://github.com/aregsar/mvcapp.
Testing the Global Exception Handler middleware
To do a quick test of the installed the global exception handler middleware, I added an Ajax
action method to the HomeController
class. The method normally returns JSON data but throws an exception if the route contains the optional id parameter.
I also modified the Privacy
action method that normally returns the Privacy view but throws an exception if the route contains the id parameter.
Here is the code for these action methods:
public IActionResult Privacy(int? id)
{
if(id.HasValue)
throw new Exception("privacy page exception");
return View();
}
public IActionResult Ajax(int? id)
{
if(id.HasValue)
throw new Exception("ajax exception");
return Json(new {name="ajax"});
}
Now, looking in the Startup.Configure(...)
method we can see that the global exception handler middleware is installed in the middleware pipeline only for production builds.
Therefore, to run the server in production mode, I added a Production run configuration profile in the profiles section of the propertieslaunchSettings.json file.
Here is the production configuration from the launchSettings file:
"prod": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
After adding the configuration profile we can use the dotnet run command with the –launch-profile option to run the app in production mode.
dotnet run --launch-profile prod
We can now quickly test the global exception handling middleware code by issuing curl
commands against the Ajax
action endpoint.
To do so we can open a new terminal tab and curl a request to the https://localhost:5001/home/ajax
URL:
curl -i -H "Accept: application/json" https://localhost:5001/home/ajax
HTTP/1.1 200 OK
Date: Thu, 11 Apr 2019 22:47:56 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
{"name":"ajax"}
We can see the normal JSON response of the Ajax action method since there was no unhandled exception.
Next we can add an id parameter to the URL to activate the exception in the Ajax action method:
curl -i -H "Accept: application/json" https://localhost:5001/home/ajax/1
HTTP/1.1 500 Internal Server Error
Date: Thu, 11 Apr 2019 22:46:27 GMT
Content-Type: application/json
Server: Kestrel
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Expires: -1
{
"title": "Unexpected error",
"status": 500,
"detail": "test exceptionrn nrn at mvcapp.Controllers.HomeController.ajax(Nullable`1 id) in /Users/aregsarkissian/projects/asp3/mvcapp/Controllers/HomeController.cs:line 29n at lambda_method(Closure , Object , Object[] )n at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)n at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()n at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)n at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)n at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)n at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)",
"instance": "9f238f4e-97b4-478d-9ee3-96e91cb1a93c"
}
This time we can see that the response includes the JSON formatted exception data returned by the global exception handler.
Also if we look at the terminal tab where we ran the application, we can see that the unhandled exception is logged as JSON data to the console by the global exception handler.
Next we can quickly test the global exception handler when sending requests to the Privacy action method, by using the web browser to navigate to the Privacy endpoint URL:
https://localhost:5001/home/privacy
We can see the normal privacy HTML page response displayed in the browser.
Finally we can add the id parameter to the Privacy endpoint URL and navigate to the URL to activate the exception in the Privacy action method:
https://localhost:5001/home/privacy/1
This time we can see that we are redirected to a server error page as usual for HTML endpoints that throw unhandled exceptions.
Conclusion
It is easy to add a global exception handling middleware to ASP.NET Core MVC applications to perform custom exception handling.
ASP.NET Core gives us all the facilities that we need to access information in the request headers and the exception data to make our own decision on how we want to respond to unhandled application errors.
Thanks for reading
This article guides you through the AJAX basics and gives you some simple hands-on examples to get you started.
What’s AJAX?
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest
object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its «asynchronous» nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
The two major features of AJAX allow you to do the following:
- Make requests to the server without reloading the page
- Receive and work with data from the server
Step 1 – How to make an HTTP request
To make an HTTP request to the server with JavaScript, you need an instance of an object with the necessary functionality. This is where XMLHttpRequest
comes in.
const httpRequest = new XMLHttpRequest();
After making a request, you will receive a response back. At this stage, you need to tell the XMLHttpRequest
object which JavaScript function will handle the response, by setting the onreadystatechange
property of the object to the function called when the request changes state, like this:
function handler() {
// Process the server response here.
}
httpRequest.onreadystatechange = handler;
Note that there are no parentheses or parameters after the function name, because you’re assigning a reference to the function, rather than actually calling it. Alternatively, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called «anonymous functions») to define the actions that will process the response, like this:
httpRequest.onreadystatechange = () => {
// Process the server response here.
};
Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open()
and send()
methods of the HTTP request object, like this:
httpRequest.open("GET", "http://www.example.org/some.file", true);
httpRequest.send();
- The first parameter of the call to
open()
is the HTTP request method – GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods, check the specification. - The second parameter is the URL you’re sending the request to. As a security feature, you cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on all of your pages or you will get a «permission denied» error when you call
open()
. A common pitfall is accessing your site bydomain.tld
, but attempting to call pages withwww.domain.tld
. If you really need to send a request to another domain, see HTTP access control (CORS). - The optional third parameter sets whether the request is asynchronous. If
true
(the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive. This is the first A in AJAX.
The parameter to the send()
method can be any data you want to send to the server if POST
-ing the request. Form data should be sent in a format that the server can parse, like a query string:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
or other formats, like multipart/form-data
, JSON, XML, and so on.
Note that if you want to POST
data, you may have to set the MIME type of the request. For example, use the following before calling send()
for form data sent as a query string:
httpRequest.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
Step 2 – Handling the server response
When you sent the request, you provided the name of a JavaScript function to handle the response:
httpRequest.onreadystatechange = nameOfTheFunction;
What should this function do? First, the function needs to check the request’s state. If the state has the value of XMLHttpRequest.DONE
(corresponding to 4), that means that the full server response was received and it’s OK for you to continue processing it.
if (httpRequest.readyState === XMLHttpRequest.DONE) {
// Everything is good, the response was received.
} else {
// Not ready yet.
}
The full list of the readyState
values is documented at XMLHTTPRequest.readyState and is as follows:
- 0 (uninitialized) or (request not initialized)
- 1 (loading) or (server connection established)
- 2 (loaded) or (request received)
- 3 (interactive) or (processing request)
- 4 (complete) or (request finished and response is ready)
Next, check the HTTP response status codes of the HTTP response. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a 200 OK
response code.
if (httpRequest.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
// For example, the response may have a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}
After checking the state of the request and the HTTP status code of the response, you can do whatever you want with the data the server sent. You have two options to access that data:
httpRequest.responseText
– returns the server response as a string of texthttpRequest.responseXML
– returns the response as anXMLDocument
object you can traverse with JavaScript DOM functions
Note that the steps above are valid only if you used an asynchronous request (the third parameter of open()
was unspecified or set to true
). If you used a synchronous request you don’t need to specify a function, but this is highly discouraged as it makes for an awful user experience.
Step 3 – A Simple Example
Let’s put it all together with a simple HTTP request. Our JavaScript will request an HTML document, test.html
, which contains the text «I’m a test.» Then we’ll alert()
the contents of the response. Note that this example uses vanilla JavaScript — no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory.
<button id="ajaxButton" type="button">Make a request</button>
<script>
(() => {
let httpRequest;
document
.getElementById("ajaxButton")
.addEventListener("click", makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert("Giving up :( Cannot create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open("GET", "test.html");
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert("There was a problem with the request.");
}
}
}
})();
</script>
In this example:
- The user clicks the «Make a request» button;
- The event handler calls the
makeRequest()
function; - The request is made and then (
onreadystatechange
) the execution is passed toalertContents()
; alertContents()
checks if the response was received and OK, thenalert()
s the contents of thetest.html
file.
Note: If you’re sending a request to a piece of code that will return XML, rather than a static HTML file, you must set response headers to work in Internet Explorer. If you do not set header Content-Type: application/xml
, IE will throw a JavaScript «Object Expected» error after the line where you tried to access an XML element.
Note: If you do not set header Cache-Control: no-cache
the browser will cache the response and never re-submit the request, making debugging challenging. You can also add an always-different GET parameter, like a timestamp or random number (see bypassing the cache)
Note: If the httpRequest
variable is used globally, competing functions calling makeRequest()
can overwrite each other, causing a race condition. Declaring the httpRequest
variable local to a closure containing the AJAX functions avoids this.
In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange
method when accessing the response status. To mitigate this problem, you could wrap your if...else
statement in a try...catch
:
function alertContents() {
try {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert("There was a problem with the request.");
}
}
} catch (e) {
alert(`Caught Exception: ${e.description}`);
}
}
Step 4 – Working with the XML response
In the previous example, after receiving the response to the HTTP request we used the request object’s responseText
property, which contained the contents of the test.html
file. Now let’s try the responseXML
property.
First off, let’s create a valid XML document that we’ll request later on. The document (test.xml
) contains the following:
<?xml version="1.0" ?>
<root> I'm a test. </root>
Next, in makeRequest()
, we need to replace test.html
with the XML file we just created:
httpRequest.open("GET", "test.xml");
Then in alertContents()
, we need to replace the line alert(httpRequest.responseText);
with:
const xmldoc = httpRequest.responseXML;
const root_node = xmldoc.querySelector("root");
alert(root_node.firstChild.data);
This code takes the XMLDocument
object given by responseXML
and uses DOM methods to access some of the data contained in the XML document.
Step 5 – Working with data
Finally, let’s send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, test.php
, which will take the data we send and return a «computed» string — «Hello, [user data]!» — which we’ll alert().
First we’ll add a text box to our HTML so the user can enter their name:
<label>
Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
We’ll also add a line to our event handler to get the user’s data from the text box and send it to the makeRequest()
function along with the URL of our server-side script:
document.getElementById("ajaxButton").onclick = () => {
const userName = document.getElementById("ajaxTextbox").value;
makeRequest("test.php", userName);
};
We need to modify makeRequest()
to accept the user data and pass it along to the server. We’ll change the request method from GET
to POST
, and include our data as a parameter in the call to httpRequest.send()
:
function makeRequest(url, userName) {
// …
httpRequest.onreadystatechange = alertContents;
httpRequest.open("POST", url);
httpRequest.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
httpRequest.send(`userName=${encodeURIComponent(userName)}`);
}
The function alertContents()
can be written the same way it was in Step 3 to alert our computed string, if that’s all the server returns. However, let’s say the server is going to return both the computed string and the original user data. So if our user typed «Jane» in the text box, the server’s response would look like this:
{ "userData": "Jane", "computedString": "Hi, Jane!" }
To use this data within alertContents()
, we can’t just alert the responseText
, we have to parse it and alert computedString
, the property we want:
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
const response = JSON.parse(httpRequest.responseText);
alert(response.computedString);
} else {
alert("There was a problem with the request.");
}
}
}
The test.php
file should contain the following:
$name = $_POST['userName'] ?? 'no name';
$computedString = "Hi, " . $name . "!";
$array = ['userName' => $name, 'computedString' => $computedString];
echo json_encode($array);
For more on DOM methods, be sure to check out Document Object Model (DOM).
Simple timed XHR example
Another simple example follows — here we are loading a text file via XHR, the structure of which is assumed to be like this:
TIME: 312.05 TIME: 312.07 TIME: 312.10 TIME: 312.12 TIME: 312.14 TIME: 312.15
Once the text file is loaded, we split()
the items into an array at each newline character (n
— basically where each line break is in the text file), and then print the complete list of timestamps, and the last timestamp, onto the page.
This is repeated every 5 seconds, using a setInterval()
call. The idea would be that a server-side script of some kind would continually update the text file with new timestamps, and our XHR code would be used to report the latest timestamp on the client-side.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>XHR log time</title>
<style></style>
</head>
<body>
<p id="writeData" class="data">Off-Line</p>
<p id="lastStamp">No Data yet</p>
<script>
const fullData = document.getElementById("writeData");
const lastData = document.getElementById("lastStamp");
function fetchData() {
console.log("Fetching updated data.");
const xhr = new XMLHttpRequest();
xhr.open("GET", "time-log.txt", true);
xhr.onload = () => {
updateDisplay(xhr.response);
};
xhr.send();
}
function updateDisplay(text) {
fullData.textContent = text;
const timeArray = text.split("n");
// included because some file systems always include a blank line at the end of text files.
if (timeArray[timeArray.length - 1] === "") {
timeArray.pop();
}
lastData.textContent = timeArray[timeArray.length - 1];
}
setInterval(fetchData, 5000);
</script>
</body>
</html>