jQuery AJAX

AJAX lets you fetch or send data to a server without reloading the page.

$.ajax()

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

Shorthand Methods

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

$.post('/api/users', { name: 'Sita', age: 21 }, function(data) {
  console.log('Created:', data);
});

$('#result').load('/page.html #content');

$.getJSON()

JavaScript
$.getJSON('/api/products', function(products) {
  products.forEach(function(p) {
    $('#list').append('<li>' + p.name + ' — Rs. ' + p.price + '</li>');
  });
});

Sending JSON

JavaScript
$.ajax({
  url: '/api/users',
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({ name: 'Sita', age: 21 }),
  success: function(response) { console.log('Success:', response); }
});

Tips

  • Use $.getJSON() for simple GET requests.
  • Always handle errors.
  • For new projects, prefer fetch() API.

Next: effects.