Skip to content

Commit 77d69b3

Browse files
committed
Page in the official documentation on ajax requests with IncomingRequest::isAJAX() [ci skip]
1 parent 85f8951 commit 77d69b3

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
##############
2+
AJAX Requests
3+
##############
4+
5+
The ``IncomingRequest::isAJAX()`` method uses the ``X-Requested-With`` header to define whether the request is XHR or normal. However, the most recent JavaScript implementations (ie fetch) no longer send this header along with the request, thus the use of ``IncomingRequest::isAJAX()`` becomes less reliable, because without this header it is not possible to define whether the request is or not XHR.
6+
7+
To get around this problem, the most efficient solution (so far) is to manually define the request header, forcing the information to be sent to the server, which will then be able to identify that the request is XHR.
8+
9+
Here's how to force the ``X-Requested-With`` header to be sent in the Fetch API and other JavaScript libraries.
10+
11+
Fetch API
12+
=========
13+
14+
fetch(url, {
15+
method: "get",
16+
headers: {
17+
"Content-Type": "application/json",
18+
"X-Requested-With": "XMLHttpRequest"
19+
}
20+
21+
22+
jQuery
23+
======
24+
25+
For libraries like jQuery for example, it is not necessary to make explicit the sending of this header, because according to the official documentation <https://api.jquery.com/jquery.ajax/> it is a standard header for all requests ``$.ajax()``. But if you still want to force the shipment to not take risks, just do it as follows:
26+
27+
$.ajax({
28+
url: "your url",
29+
headers: {'X-Requested-With': 'XMLHttpRequest'}
30+
});
31+
32+
33+
VueJS
34+
=====
35+
36+
In VueJS you just need to add the following code to the ``created`` function, as long as you are using Axios for this type of request.
37+
38+
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
39+
40+
41+
React
42+
=====
43+
44+
axios.get("your url", {headers: {'Content-Type': 'application/json'}})

0 commit comments

Comments
 (0)