Ajax Form Handler
The ajaxFormHandler
is a utility designed to provide seamless AJAX-based form submissions. It comes with a suite of features to handle the submission process, including feedback to the user, custom headers, and response handling.
Setup:
Before using the ajaxFormHandler
, ensure that the ajax-form-handler.js
script is included in your base.html
file at the bottom, and before any other JavaScript blocks:
<script src="/assets/js/ajax-form-handler.js"></script>
{% block javascript %}{% endblock %}
Features:
- Dynamic script loading: Loads
toasts.js
if not already present on the page. - Customizable handlers for various AJAX events.
- Customizable headers for the AJAX requests.
- Button spinner for visual feedback during request processing.
- Notification via cookies for post-redirection messages.
- Automatic handling of forms associated with buttons having class
.ajax-handler
.
API Methods:
Handlers
onSuccess(callback)
: Set a custom success callback.onError(callback)
: Set a custom error callback.onBeforeSend(callback)
: Set a custom before-send callback.onCompleted(callback)
: Set a custom completion callback.
Utilities
setHeader(key, value)
: Add or modify headers for the AJAX request.setData(data)
: Merge custom data into the form data.removeSpinnerButton(buttonData)
: Manually remove the spinner from a button.redirect(response)
: Redirect to a URL specified in the response and set a cookie notification if needed.
Usage Examples:
1. Attaching a custom success handler:
ajaxFormHandler.onSuccess(function(response, buttonData) {
console.log("Custom success handler:", response);
});
2. Setting custom headers:
ajaxFormHandler.setHeader('Authorization', 'Bearer YOUR_TOKEN');
3. Adding custom data to the form submission:
ajaxFormHandler.setData({
extraField1: 'value1',
extraField2: 'value2'
});
Note: To utilize the ajaxFormHandler
, ensure that the button triggering the form submission has the class .ajax-handler
and a data-form-id
attribute pointing to the form's ID.