-
Notifications
You must be signed in to change notification settings - Fork 508
ajax
Forms and links marked with "data-remote" attribute are submitted with jQuery.ajax()
. In addition to normal jQuery Ajax "global" events, these custom events are fired from those DOM elements:
event name | extra parameters * | when |
---|---|---|
ajax:before |
before the whole ajax business , aborts if stopped | |
ajax:beforeSend |
[xhr, settings] | before the request is sent, aborts if stopped |
ajax:success |
[evt, data, status, xhr] | after completion, if the HTTP response was a success |
ajax:error |
[xhr, status, error] | after completion, if the server returned an error ** |
ajax:complete |
[xhr, status] | after the request has been completed, no matter what outcome |
ajax:aborted:required |
[elements] | when there are blank required fields in a form, submits anyway if stopped |
ajax:aborted:file |
[elements] | if there are non-blank input:file fields in a form, aborts if stopped |
* All handlers bound to jQuery events are always passed the event object as the first argument. Extra parameters denotes the parameters passed after the event argument. E.g. if the Extra parameters are listed as [xhr, settings]
, then to access them, you would define your handler with function(event, xhr, settings){}
. See this article for a more in-depth explanation.
** Opera is inconsistent in its handling of jQuery ajax error responses, so relying on the values of xhr.status
, status
, or error
in an ajax:error
callback handler may cause inconsistent behavior in Opera.
If you stop ajax:before
or ajax:beforeSend
, the Ajax request will never take place. The ajax:before
event is also useful for manipulating form data before serialization. The ajax:beforeSend
event is also useful for adding custom request headers.
If you stop the ajax:aborted:required
event, the default behavior of aborting the form submission will be canceled, and thus the form will be submitted anyway.
If you stop the ajax:aborted:file
event, the default behavior of allowing the browser to submit the form via normal means (i.e. non-AJAX submission) will be canceled and the form will not be submitted at all. This is useful for implementing your own AJAX file upload workaround.
When processing a request failed on the server, it might return the error message as HTML:
$('#account_settings').on('ajax:error', function(event, xhr, status) {
// insert the failure message inside the "#account_settings" element
$(this).append(xhr.responseText)
});
Set custom HTTP headers just for a specific type of forms:
$('form.new_conversation').on('ajax:beforeSend', function(event, xhr, settings) {
xhr.setRequestHeader('X-Awesome', 'enabled');
});