Introduction to AJAX
AJAX (Asynchronous JavaScript and XML) anables web pages to communicate with servers without reloading the entire page. This article covers practical AJAX implementation paterns.
1. Basic AJAX Implementation
The following example demonstrates how to send form data to a server using jQuery's AJAX function:
The corresponding Django view handles the incoming request:
if name and len(name) > 3:
Host.objects.create(
hostname=name,
ip=ip,
port=port,
group_id=group
)
return HttpResponse('success')
else:
return HttpResponse('Name too short')
</div>### 3. Working with JSON Responses
For more complex data structures, return JSON from the server:
<div>```
$.ajax({
url: '/api/data/endpoint',
method: "POST",
data: {'key1': 456, 'key2': "administrator"},
success: function(response) {
// Server returns a JSON string, parse it
var data = JSON.parse(response);
console.log(data);
}
});
Instead of manually collecting form values, use jQuery's serialize method:
5. Global AJAX Configuration with CSRF Protection
Configure CSRF tokens globally for all AJAX requests:
$('#login_button').on('click', function() {
$.ajax({
url: '/auth/login/',
method: 'GET',
data: {'username': 'admin', 'password': 'secret'},
success: function(response) {
console.log('Login successful');
}
});
});
});
</div>Alternatively, you can include the CSRF token in the request headers per call:
<div>```
$.ajax({
url: '/api/secure endpoint/',
method: 'POST',
data: {'data': 'value'},
headers: {'X-CSRFToken': $.cookie('csrftoken')},
success: function(response) {}
});