taki3 edited this page Jan 30, 2018 · 59 revisions

Custom events fired during "data-remote" requests

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 parameters after event* when
ajax:before before the whole ajax business , aborts if stopped
ajax:beforeSend [xhr, settings] before the request is sent, aborts if stopped
ajax:send [xhr] when the request is sent
ajax:success [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.

Stoppable events

If you stop ajax:before or ajax:beforeSend by returning false from the handler method, 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.

Example usage

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, error) {
  // insert the failure message inside the "#account_settings" element

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');
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.