AJAX with jQuery

Harry · 11 Sep 2026 · 10 views

Fetching Data Without Reloading

jQuery wraps the painful XMLHttpRequest API into a small, consistent set of methods.

$.get and $.post

$.get('/api/users', function (data) {
  console.log(data);
});

$.post('/api/users', { name: 'Priya' }, function (res) {
  console.log('Created', res);
});

Loading HTML Into an Element

$('#content').load('/partials/about.html #main');

.load fetches the URL and drops the matched fragment into the selection.

Full $.ajax Control

$.ajax({
  url: '/api/users',
  method: 'GET',
  dataType: 'json',
  success: function (data) {
    render(data);
  },
  error: function (xhr, status) {
    console.error(status, xhr.status);
  }
});

Promises in jQuery AJAX

$.get('/api/users')
  .done(render)
  .fail(function () { alert('Request failed'); })
  .always(function () { spinner.hide(); });

jQuery AJAX methods return a jqXHR object with Promise-like done/fail/always methods.

Security Note

When sending data to the server from a POST, include a CSRF token header. In a Spring Boot app with Spring Security, jQuery can add it automatically:

var token = $('meta[name="_csrf"]').attr('content');
$.ajaxSetup({ beforeSend: function (xhr) {
  xhr.setRequestHeader('X-CSRF-TOKEN', token);
}});

Key Points

  • $.get/$.post cover the common cases.
  • .load() injects fetched HTML into the page.
  • $.ajax gives full control over method, headers and dataType.
  • Use done/fail/always for promise-style handling.
Share this post:

Comments (0)

Please login or register to comment.