๐Ÿ’ฒ jQuery Essentials

jQuery AJAX: A Complete Guide with Real Examples

By The CodeCraft Teamยทยท8 min read
jQuery AJAX request in a code editor

Long before fetch existed, jQuery's $.ajax was how the web talked to servers without reloading. It still works fine โ€” and if you're maintaining a legacy app, knowing it well saves hours.

Simple GET and POST

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

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

$.ajax โ€” the full toolbox

$.ajax({
  url: '/api/users',
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({ name: 'Ada' }),
  dataType: 'json',
  timeout: 10000
})
  .done(res => console.log(res))
  .fail((xhr, status, err) => console.error(status, err))
  .always(() => hideSpinner());

Loading JSON the short way

$.getJSON('/api/posts').done(posts => render(posts));

Sending form data

$('#myForm').on('submit', function (e) {
  e.preventDefault();
  $.post('/save', $(this).serialize(), () => alert('Saved!'));
});

Error handling that doesn't swallow problems

  • Always attach a .fail() or error callback
  • Set a sensible timeout โ€” networks fail silently otherwise
  • Show the user something when a request fails โ€” not just a silent log

Migrating to fetch

// jQuery
$.get('/api/users').done(render);

// fetch equivalent
fetch('/api/users')
  .then(r => r.json())
  .then(render);

Frequently asked questions

Is jQuery AJAX still safe to use?

Yes. It's stable and well-supported. Just don't add it to a new project that doesn't already depend on jQuery.

Does $.ajax support promises?

Yes โ€” it returns a jqXHR which is a thenable. You can use .then() or await it.

External references

Enjoyed this article?

Share it with a fellow developer or explore more tutorials in our blog.

More articles

Related articles