Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

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.

MethodPurposeHas Body?Idempotent?
GETRetrieve dataNoYes
POSTCreate a resourceYesNo
PUTReplace a resource entirelyYesYes
PATCHPartially update a resourceYesNo
DELETERemove a resourceOptionalYes
HEADLike GET but no response bodyNoYes
GET and POST Requests with XHR
// ---- 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
}));
PUT, PATCH, and DELETE with Fetch
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().

Setting Custom Request Headers
// ---- 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.