AJAX Request Types
HTTP Methods in AJAX
AJAX requests use standard HTTP methods. Choosing the right method is important for RESTful API design and correct server-side handling.
| Method | Purpose | Has Body? | Idempotent? |
|---|---|---|---|
| GET | Retrieve data | No | Yes |
| POST | Create a resource | Yes | No |
| PUT | Replace a resource entirely | Yes | Yes |
| PATCH | Partially update a resource | Yes | No |
| DELETE | Remove a resource | Optional | Yes |
| HEAD | Like GET but no response body | No | Yes |
// ---- GET Request ----
// Query parameters are appended to the URL
const params = new URLSearchParams({ search: 'javascript', page: 1 });
const xhrGet = new XMLHttpRequest();
xhrGet.open('GET', `/api/posts?${params}`, true);
xhrGet.onload = () => console.log(JSON.parse(xhrGet.responseText));
xhrGet.send(); // GET has no body
// ---- POST Request ----
// Data is sent in the request body
const xhrPost = new XMLHttpRequest();
xhrPost.open('POST', '/api/posts', true);
// Tell the server we're sending JSON
xhrPost.setRequestHeader('Content-Type', 'application/json');
xhrPost.onload = function () {
if (xhrPost.status === 201) {
console.log('Created:', JSON.parse(xhrPost.responseText));
}
};
// Serialize data to JSON and send in the body
xhrPost.send(JSON.stringify({
title: 'My New Post',
body: 'Post content here',
userId: 1
}));
const headers = { 'Content-Type': 'application/json' };
// ---- PUT — replace entire resource ----
fetch('/api/posts/1', {
method: 'PUT',
headers,
body: JSON.stringify({ title: 'Updated Title', body: 'Updated body', userId: 1 })
}).then(res => res.json()).then(console.log);
// ---- PATCH — update specific fields only ----
fetch('/api/posts/1', {
method: 'PATCH',
headers,
body: JSON.stringify({ title: 'Only Title Changed' })
}).then(res => res.json()).then(console.log);
// ---- DELETE — remove a resource ----
fetch('/api/posts/1', {
method: 'DELETE'
}).then(res => {
if (res.ok) console.log('Post deleted successfully');
});
// ---- HEAD — check if resource exists without downloading body ----
fetch('/api/posts/1', { method: 'HEAD' }).then(res => {
console.log('Status:', res.status);
console.log('Content-Type:', res.headers.get('Content-Type'));
});
Setting Request Headers
Request headers provide additional information to the server — such as the content type, authentication tokens, or custom metadata. Use setRequestHeader() with XHR or the headers option with fetch().
// ---- XHR: setRequestHeader() ----
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/secure-endpoint', true);
// Must be called AFTER open() and BEFORE send()
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer eyJhbGciOiJIUzI1NiJ9...');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // common AJAX identifier
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = () => console.log(xhr.responseText);
xhr.send(JSON.stringify({ action: 'getData' }));
// ---- Fetch: headers option ----
fetch('/api/secure-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9...',
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json'
},
body: JSON.stringify({ action: 'getData' })
}).then(res => res.json()).then(console.log);
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.