jQuery Ajax Methods: $.ajax(), $.get(), $.post(), and load()
1. Core Ajax Methods
1) $.ajax()
The $.ajax() method is the most flexible way to make Ajax requests in jQuery.
Basic Syntax:
$.ajax({
type: 'GET', // HTTP method (GET, POST, PUT, DELETE)
url: 'https://api.example.com/data', // Request URL
data: {}, // Request parameters
beforeSend: function() {
// Executes before the request is sent
$('#loading').show();
},
success: function(response) {
// Executes on successful response
console.log(response);
},
complete: function() {
// Executes after request completes (success or error)
$('#loading').hide();
},
error: function(xhr, status, error) {
// Executes on request failure
console.error('Request failed:', status, error);
}
});
Example: POST Request
<body>
<button id="submitBtn">Submit POST Request</button>
<script>
$(function() {
$('#submitBtn').on('click', function() {
$.ajax({
type: 'POST',
url: 'http://api.example.com/books',
data: {
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
publisher: 'Scribner'
},
success: function(result) {
console.log('Book added:', result);
}
});
});
});
</script>
</body>
2) $.get()
The $.get() method is a shorthand for making GET requests.
Syntax with URL parameters:
$.get('https://api.example.com/shop?id=123&category=books',
function(response) {
console.log(response);
}
);
Syntax with data object:
$.get('https://api.example.com/shop',
{ id: 123, category: 'books' },
function(response) {
console.log(response);
}
);
3) $.post()
The $.post() method is a shorthand for making POST requests.
Syntax:
$.post('https://api.example.com/shop',
{ pageSize: 10, pageNumber: 1 },
function(response) {
console.log(response);
}
);
2. jQuery load() Method
The load() method loads data from the server and places the returned data into the selected element.
Syntax:
$(function() {
$('#loadButton').click(function() {
$('#contentContainer').load('data.html', function(responseText, statusText, xhr) {
console.log('Response:', responseText); // Returned content
console.log('Status:', statusText); // Request status: success or error
console.log('XHR object:', xhr); // Ajax instance object
});
});
});
3. $.ajax() Configuration Parameters
Essential Parameters
url (String)
- Default: Current page address
- The URL to send the request to
type (String)
- Default: 'GET'
- HTTP method: 'GET', 'POST', 'PUT', 'DELETE'
- Note: PUT and DELETE are supported by most modern browsers
async (Boolean)
- Default: true
- Set to false for synchronous requests
- Warning: Synchronous requests block the browser until complete
cache (Boolean)
- Default: true (false when dataType is 'script')
- Set to false to prevent loading from browser cache
data (Object or String)
- Data to send to the server
- Automatically converted to query string for GET requests
- Format: {key1: 'value1', key2: 'value2'}
- Arrays: {items: ['item1', 'item2']} becomes &items=item1&items=item2
dataType (String)
- Expected data type from server response
- If not specified, jQuery infers from MIME type
- Available types:
- xml: Returns XML documant
- html: Returns HTML text (script tags execute when inserted into DOM)
- script: Returns JavaScript code (not auto-cached unless cache parameter set)
- jsonp: JSONP format for cross-domain requests
- text: Returns plain text string
Callback Functions
complete (Function)
- Executes when request completes (both success and error)
- Parameters: XMLHttpRequest object, status string
complete: function(xhr, status) {
// 'this' refers to the options object passed to $.ajax()
console.log('Request completed with status:', status);
}
succsess (Function)
- Executes on successful response
- Parameters: processed data (based on dataType), status string
success: function(data, status) {
// data could be XML, JSON, HTML, or text
// 'this' refers to the options object passed to $.ajax()
console.log('Success:', data);
}
error (Function)
- Executes on request failure
- Parameters: XMLHttpRequest object, error description, error object
error: function(xhr, status, error) {
// Typically only status or error contains information
// 'this' refers to the options object passed to $.ajax()
console.error('Error:', status, error);
}
contentType (String)
- Default: 'appplication/x-www-form-urlencoded'
- Content encoding type when sending data to server
- Suitable for most applications
Summary
jQuery provides multiple methods for making Ajax requests:
- $.ajax(): Most flexible, full control over request configuration
- $.get(): Shorthand for GET requests
- $.post(): Shorthand for POST requests
- load(): Loads HTML content directly into elements
Each method supports various configuration options and callback functions to handle different stages of the request lifecycle.