Skip to content
neerajdotname edited this page Apr 13, 2011 · 61 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 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 [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

If you stop ajax:beforeSend, the Ajax request will never take place. This event is also useful for adding custom request headers.

Example usage

When processing a request failed on the server, it might return the error message as HTML:

$('#account_settings').live('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').live('ajax:beforeSend', function(event, xhr, settings) {
  xhr.setRequestHeader('X-Awesome', 'enabled');
})
Clone this wiki locally