SyntaxStudy
Sign Up
jQuery jQuery AJAX and REST APIs
jQuery Advanced 7 min read

jQuery AJAX and REST APIs

REST APIs use different HTTP verbs — GET, POST, PUT, PATCH, DELETE — to represent different operations on resources. jQuery's $.ajax() supports all HTTP methods, making it straightforward to build a full CRUD client for any REST backend.

CRUD with $.ajax()

Map each REST operation to the appropriate verb. Always set contentType: 'application/json' and serialise the payload with JSON.stringify() when sending structured data to modern APIs. The server response should be parsed automatically when dataType: 'json' is set.

Authentication Headers

Many APIs require an Authorization header with a token. Set it globally for all requests using $.ajaxSetup(), or pass it per-request via the headers option.

  • GET — fetch resource
  • POST — create resource
  • PUT / PATCH — update resource
  • DELETE — delete resource
  • headers option — set custom headers like Authorization

Use $.ajaxSetup() sparingly and only for truly global defaults. Per-request options always override global defaults, so you can override the token for specific unauthenticated endpoints.

Example
// Global auth header
$.ajaxSetup({
    headers    : { 'Authorization': 'Bearer ' + localStorage.getItem('token') },
    contentType: 'application/json',
    dataType   : 'json'
});

// CREATE
$.ajax({ url: '/api/posts', method: 'POST',
    data: JSON.stringify({ title: 'Hello', body: 'World' }) });

// READ
$.ajax({ url: '/api/posts/42', method: 'GET' })
    .done(function (post) { console.log(post.title); });

// UPDATE
$.ajax({ url: '/api/posts/42', method: 'PUT',
    data: JSON.stringify({ title: 'Updated Title' }) });

// DELETE
$.ajax({ url: '/api/posts/42', method: 'DELETE' })
    .done(function () { $('#post-42').remove(); });
Pro Tip

Set global defaults with $.ajaxSetup() for auth headers and content type, then override per-request as needed.