jQuery AJAX

AJAX lets your page fetch or send data without reloading. jQuery wraps XMLHttpRequest with easy methods and promises-like APIs.

Quick Reference

MethodDescriptionExample
$.get(url, [data], [cb])GET request; callback on success.$.get('/user/1', d => ...)
$.post(url, [data], [cb])POST request shortcut.$.post('/save', {name:'S'})
$.ajax(opts)Low-level, full control (method, headers, timeout, etc.).$.ajax({url:'/x',method:'GET'})
$.getJSON(url, [data], [cb])GET JSON and parse automatically.$.getJSON('/todos/1')
$(form).serialize()Encode form fields as query string.$('#f').serialize()
$.ajaxSetup(opts)Set global defaults for future AJAX calls.$.ajaxSetup({timeout:8000})
$.when(a,b)Wait for multiple deferreds to complete.$.when($.get('/a'), $.get('/b'))
.done() / .fail() / .always()Promise-like handlers on jqXHR.$.get('/x').done(fn).fail(fn)
ajaxStart / ajaxStopGlobal hooks for all AJAX on the page.$(document).ajaxStart(cb)
Note: Cross-origin requests and some demo endpoints may be blocked by CORS in local files. On your site, these examples will work if the browser allows the request.

1) $.get()


$.get('https://jsonplaceholder.typicode.com/users/1', function(data){
  console.log(data);
});

2) $.post()


$.post('https://reqres.in/api/users', { name: 'Sonu', job: 'writer' })
  .done(function(resp){ console.log(resp); })
  .fail(function(){ alert('POST failed'); });

3) $.ajax() (full control)


$.ajax({ url: 'https://jsonplaceholder.typicode.com/posts/1', method: 'GET',
  dataType: 'json', timeout: 5000 })
  .done(function(d){ console.log(d); })
  .fail(function(xhr, status){ console.warn(status); })
  .always(function(){ console.log('done'); });

4) $.getJSON()


$.getJSON('https://jsonplaceholder.typicode.com/todos/1', function(data){
  console.log(data);
});

5) Forms: serialize() + $.ajax


$('#f').on('submit', function(e){
  e.preventDefault();
  $.ajax({ url: '/submit', method: 'POST', data: $(this).serialize() });
});

6) Global Events


$(document).ajaxStart(function(){ $('#spinner').show(); });
$(document).ajaxStop(function(){ $('#spinner').hide(); });

7) Error Handling


$.ajax({ url: '/does-not-exist' })
  .fail(function(xhr){ console.log('Status: ' + xhr.status); });

8) Promises: done/fail/always & $.when()


var a = $.get('/a'), b = $.get('/b');
$.when(a, b).done(function(){ console.log('both done'); });

9) Global Defaults: $.ajaxSetup()


$.ajaxSetup({ timeout: 8000, headers: { 'X-Demo': 'Codingwithsonu' } });
Security: Never inject untrusted data into html(); prefer text(). Validate/escape user input on the server.