November 15, 2014 · ajax jquery

Override jQuery.ajax handler

Table of contents:

  1. Introduction
  2. How to override Jquery ajax function?
  3. Source code

Introduction

This is tutorial on how to override default JQuery.ajax handler. Why would you need to override default JQuery.ajax handler at all?

Here are several use cases that I can think of:

  1. You can achieve some global AJAX success / error handling.
  2. Forbid execution of default callbacks attached to the resulting deferred.promise returned by the JQuery.ajax handler.

How to override Jquery ajax function?

Create object with method definitions for our sample

 var App = {};

 App.Util = {
     customHandler: function(p) {},
     validateAjaxResponse: function(data) {},
     Ajax : function(options) {}
 }

We have created several method definitions for our example.
App.Util.customHandler - This function is invoked instead one or multiple callback functions that are attached to the promise().done() / promise().fail() handlers. App.Util.validateAjaxResponse - If the result of this function is "true" callback functions attached to the promise().done() / promise().fail() are invoked, otherwise our App.Util.customHandler is invoked. App.Util.Ajax - This is our implementation that will override default JQuery.ajax implementation.

Save default ajax handler to the temporary variable

 var t = $.ajax;

We are saving default implementation of the http://api.jquery.com/jQuery.ajax/ function to the temporary variable.

Replace default $.ajax with custom ajax function

 $.ajax = App.Util.Ajax;

We are overriding default JQuery.ajax implementation. Remember that we saved JQuery.ajax to the temporary variable in the previous step, in order to use when wee need it.

Write code for your new $.ajax handler

 App.Util.Ajax = function(options) {
     return t(options).pipe(function(data) { 
         if (App.Util.validateAjaxResponse(data)) {
             return data;
         } else {
             App.Util.customHandler(data);
             return $.Deferred().promise();
         }
     });
 }

Let me explain what we just did here:

  1. Remember that temporary variable "t" with the default http://api.jquery.com/jQuery.ajax/ implementation? We are going to invoke "t" function and filter result.
  2. We are using deferred.pipe() to filter result of a default JQuery.ajax invocation.
  3. We are validating response data with the App.Util.validateAjaxResponse function and if there are no errors deferred.pipe() is going to resolve / reject new Deffered with the propagated data object.

If App.Util.validateAjaxResponse function returns false, App.Util.customHandler is invoked which will return new deferred.promise() that is never resolved/rejected.

If you are asking yourself why done()/fail() handlers are not triggered, it's right time to study deferred.promise() in more depth. I suggest reading jquery source code. It's the best way of finding out what is happening under the hood.

Any questions?

Source code

Check interactive source code version on jsbin

 var App = {};

 App.Util = {
     customHandler: function(p) {
         console.log('Called from -> custom handler');
     },

     validateAjaxResponse: function(data) {
         return data.status === "ok" ? true : false;
     },

     Ajax : function(options) {
         return t(options).pipe(function(data) { 

             if (App.Util.validateAjaxResponse(data)) {
                 return data;
             } else {
                 App.Util.customHandler(data);
                 return $.Deferred().promise();
             }
         });
     }
 };

 var t = $.ajax;

 $.ajax = App.Util.Ajax;

 $('#load-ajax-with-ok-code, #load-ajax-with-error-code').live('click', function() {
     var d = $.ajax({
         url: $(this).attr('title'),
         context: document.body,
         dataType: 'jsonp',
     });

     d.done(function(data) {
         console.log('Called from -> Callback attached to the promise.done(): ', data);
     });

     d.fail(function(data) {
         console.log('Called from -> Callback attached to the promise.fail()', data); 
     });
 });
 <html>
 <head>
     <title></title>
     <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
     <script> CODE FROM SECTION ABOVE </script>
 </head>
 <body>
 <div>
 <a id="load-ajax-with-ok-code" href="#load-ajax-with-ok-code" title="http://echo.jsontest.com/status/ok">
 Load ajax with OK code</a> - This invokes regular .done(), .fail() handlers
 </div>
 <div>
 <a id="load-ajax-with-error-code" href="#load-ajax-with-error-code" title="http://echo.jsontest.com/status/error">
 Load ajax with error code</a> - Invokes custom handler instead handlers attached to the .done(), .fail() handlers of the promise returned by $.ajax
 </div>
 <hr/>
 <div id="result"></div>
 </body>
 </html>
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus