0
# AJAX and Remote Requests
1
2
Core AJAX functionality for making HTTP requests with Rails conventions, including automatic CSRF protection, response processing, and cross-domain detection.
3
4
## Capabilities
5
6
### AJAX Request Function
7
8
Makes AJAX requests with Rails conventions including automatic CSRF token handling and response processing.
9
10
```javascript { .api }
11
/**
12
* Make AJAX request with Rails conventions
13
* @param options - Configuration object for the request
14
* @returns XMLHttpRequest instance or false if beforeSend prevents the request
15
*/
16
function ajax(options: AjaxOptions): boolean | XMLHttpRequest;
17
18
interface AjaxOptions {
19
/** Request URL (defaults to current location) */
20
url?: string;
21
/** HTTP method (GET, POST, PUT, DELETE, etc.) */
22
type?: string;
23
/** Request data as string or FormData */
24
data?: string | FormData;
25
/** Expected response type (script, json, html, xml, text, *) */
26
dataType?: string;
27
/** Accept header value (auto-generated from dataType) */
28
accept?: string;
29
/** Callback before sending request, return false to cancel */
30
beforeSend?: (xhr: XMLHttpRequest, options: AjaxOptions) => boolean;
31
/** Success callback for 2xx responses */
32
success?: (response: any, statusText: string, xhr: XMLHttpRequest) => void;
33
/** Error callback for non-2xx responses */
34
error?: (response: any, statusText: string, xhr: XMLHttpRequest) => void;
35
/** Completion callback called regardless of success/error */
36
complete?: (xhr: XMLHttpRequest, statusText: string) => void;
37
/** Whether this is a cross-domain request */
38
crossDomain?: boolean;
39
/** Include credentials in cross-origin requests */
40
withCredentials?: boolean;
41
}
42
```
43
44
**Usage Examples:**
45
46
```javascript
47
import Rails from "@rails/ujs";
48
49
// Basic GET request
50
Rails.ajax({
51
type: "GET",
52
url: "/api/users",
53
dataType: "json",
54
success: (data) => console.log("Users:", data),
55
error: (xhr) => console.error("Error:", xhr.status)
56
});
57
58
// POST request with data
59
Rails.ajax({
60
type: "POST",
61
url: "/api/users",
62
data: "name=John&email=john@example.com",
63
success: (response) => console.log("Created:", response)
64
});
65
66
// Request with FormData
67
const formData = new FormData();
68
formData.append("file", fileInput.files[0]);
69
Rails.ajax({
70
type: "POST",
71
url: "/upload",
72
data: formData,
73
success: (result) => console.log("Uploaded:", result)
74
});
75
```
76
77
### Cross-Domain Detection
78
79
Determines if a URL represents a cross-domain request by comparing protocols and hosts.
80
81
```javascript { .api }
82
/**
83
* Determines if the request is a cross domain request
84
* @param url - URL to check for cross-domain
85
* @returns True if URL is cross-domain, false if same-origin
86
*/
87
function isCrossDomain(url: string): boolean;
88
```
89
90
**Usage Examples:**
91
92
```javascript
93
// Check if URL is cross-domain
94
if (Rails.isCrossDomain("https://api.external.com/data")) {
95
console.log("This is a cross-domain request");
96
}
97
98
// Same-origin check
99
if (!Rails.isCrossDomain("/api/local")) {
100
console.log("This is a same-origin request");
101
}
102
```
103
104
### Element Href Utility
105
106
Gets the href attribute from an element. This function can be overridden to customize link behavior.
107
108
```javascript { .api }
109
/**
110
* Get element's href attribute (overridable)
111
* @param element - Element to get href from
112
* @returns The href value
113
*/
114
function href(element: Element): string;
115
```
116
117
**Usage Examples:**
118
119
```javascript
120
const link = document.querySelector('a[data-method="delete"]');
121
const url = Rails.href(link);
122
123
// Custom href behavior (override)
124
Rails.href = function(element) {
125
// Custom logic for determining URL
126
return element.getAttribute("data-url") || element.href;
127
};
128
```
129
130
### Response Processing
131
132
The AJAX system automatically processes responses based on Content-Type headers:
133
134
- **JSON responses**: Automatically parsed with `JSON.parse()`
135
- **JavaScript responses**: Executed as inline scripts with CSP nonce support
136
- **XML/HTML/SVG responses**: Parsed with `DOMParser`
137
- **Other responses**: Returned as-is
138
139
### Accept Headers
140
141
Rails UJS sets appropriate Accept headers based on the `dataType` option:
142
143
```javascript { .api }
144
const AcceptHeaders = {
145
"*": "*/*",
146
"text": "text/plain",
147
"html": "text/html",
148
"xml": "application/xml, text/xml",
149
"json": "application/json, text/javascript",
150
"script": "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
151
};
152
```
153
154
### CSRF Integration
155
156
All AJAX requests automatically include CSRF protection:
157
158
- `X-CSRF-Token` header is added from `<meta name="csrf-token">`
159
- `X-Requested-With: XMLHttpRequest` header identifies AJAX requests
160
- Cross-domain requests skip CSRF protection
161
162
### Data Attribute Integration
163
164
Elements with `data-remote="true"` automatically trigger AJAX requests:
165
166
```html
167
<!-- Link makes AJAX request instead of page navigation -->
168
<a href="/posts/1" data-remote="true" data-method="delete">Delete</a>
169
170
<!-- Form submits via AJAX -->
171
<form action="/posts" method="post" data-remote="true">
172
<input type="text" name="title">
173
<input type="submit" value="Create">
174
</form>
175
176
<!-- Button makes AJAX request -->
177
<button data-remote="true" data-url="/api/refresh" data-method="post">Refresh</button>
178
```