views:

393

answers:

1

I'm using Rails 3 and JQuery 1.4.2 and am trying to bind to the ajax:failure callback on a given remote form submission. The callback works fine, however, the xhr variable that's passed back seems to lose the responseText attribute somehow.

Here's what my code looks like:

_form.html.haml

= form_for(object, :remote => true) do |f|
  = form fields and such...

Javascript somewhere...

 $('form').livequery('ajax:loading', function() {
    // what to do on ajax loading
}).livequery('ajax:success', function(data, status, xhr) {

}).livequery('ajax:failure', function(xhr, status, error) {
    alert(xhr.responseText);
});

I'm basically rendering the object's error messages from the controller so that I can display error notifications on this callback. The weird thing is I go into rails.js, lines 49-51

error: function (xhr, status, error) {
  el.trigger('ajax:failure', [xhr, status, error]);
}

and manually write to the console responseText, it works the way I would expect.

Am I doing something wrong? How would the xhr object change from the rails.js to my bind?

+2  A: 

I figured out the answer but am confused to why it is so. So rails.js triggers an ajax:failure event by using the following code snippet

$.ajax({
    url: url,
    data: data,
    dataType: dataType,
    type: method.toUpperCase(),
    ...
    error: function (xhr, status, error) {
        el.trigger('ajax:failure', [xhr, status, error]);
    }
});

When I bind to that event,

$('form').livequery('ajax:failure', function(xhr, status, error) {

the status var appears to have the responseText attribute and not the xhr as I would have thought.

So,

console.log(status.responseText)

spits out my response text.

The correct bind should look like this

('form').livequery('ajax:failure', function(event, xhr, status, error) {

Since the first variable is the event that fired.

ncavig
I also realized why the vars weren't matching up. Apparently since I'm binding to the event, the first variable passed in would be the actual event being thrown with the xhr, status, and error also being passed after it.
ncavig