Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is jQuery's equivalent to Prototype's Ajax.Responders.register?

Is there a jQuery equivalent to this prototype code?

Ajax.Responders.register({
  onException: function(x,y)
  {
    if(y.message!="Syntax error") new Insertion.After("toperrorbox","<p style='color:red'>"+y.message+"</p>");
  }
});
like image 587
Stijn Sanders Avatar asked Aug 04 '09 16:08

Stijn Sanders


2 Answers

Prototype's Ajax.Responders are global listeners that listen to ALL ajax events. jQuery does indeed have an equivalent. The global Ajax Events.

The syntax is a little different, due to jQuery's nature, but something similar to this should do the trick:

$('#toperrorbox').bind('ajaxError', function (event, XMLHttpRequest, ajaxOptions, thrownError) {
   // thrownError only passed if an error was caught
   // this == dom element listening
   var message = thrownError === undefined? XMLHttpRequest.responseText : thrownError.message;
   $(this).after("<p style='color:red'>"+ message +"</p>");
}

In this case, XMLHttpRequest.responseText will contain the body (if any) returned from the server on the failed request. And thrownError will contain the actual exception, which I believe you are actually after. But, I'd recommend checking to see if an exception was indeed passed in before trying to print its message, which is what I've done in my example. If it has caught an exception, it'll use that message, but if not, it'll use the server response.

It is worth noting that with jQuery, all events are always bound to something. Usually a DOM Node, but possibly the window or the document. If you wanted to do the same thing, without binding to the specific element to act on (like the above example), you could bind the event to the window and select the element(s) to work on in your callback like this:

$(window).bind('ajaxError', function (event, XMLHttpRequest, ajaxOptions, thrownError) {
   // thrownError only passed if an error was caught
   // this == dom element listening
   var message = thrownError === undefined? XMLHttpRequest.responseText : thrownError.message;
   $('#toperrorbox').after("<p style='color:red'>"+ message +"</p>");
}

This may afford you greater control over the events, as you do not have to remember which elements they were bound to, and if you didn't use anonymous functions, you could unbind specific callbacks at will.

like image 174
jason Avatar answered Nov 05 '22 09:11

jason


http://docs.jquery.com/Ajax/ajaxError#examples

$('#toperrorbox').ajaxError(function (event, request, settings) {
   $(this).after("<p style='color:red'>"+ request.responseText +"</p>");
}

Attach a function to be executed whenever an AJAX request fails.

like image 20
Philippe Avatar answered Nov 05 '22 07:11

Philippe