Note that there are some explanatory texts on larger screens.

plurals
  1. POModify ajax response before any bound callbacks get executed
    text
    copied!<p><strong>ISSUE</strong></p> <p>I needed a way to modify all ajax responses in an app before all bound callbacks are triggered.</p> <p><strong>SOLUTION</strong></p> <p>Standard ajax events, both global and local do not provide a good way to modify the response before app bound callback are triggered. </p> <p>The order by which ajax events get triggered is the one indicated in the <a href="http://docs.jquery.com/Ajax_Events" rel="nofollow">jquery's ajax event docs</a> i.e.</p> <ul> <li>ajaxStart (Global Event)</li> <li>beforeSend (Local Event)</li> <li>ajaxSend (Global Event)</li> <li>success (Local Event)</li> <li>ajaxSuccess (Global Event)</li> <li>error (Local Event)</li> <li>ajaxError (Global Event)</li> <li>complete (Local Event)</li> <li>ajaxComplete (Global Event)</li> <li>ajaxStop (Global Event)</li> </ul> <p>Notice that there is no hook executed after the response gets back from the server but before success/erorr callback are run e.g. a kind of <code>ajaxReturn</code> after <code>ajaxSend</code> but before <code>success|error</code></p> <p>The way i hacked this was to use <a href="http://api.jquery.com/jQuery.ajaxPrefilter/" rel="nofollow">$.ajaxPrefilter</a> which is executed before <code>ajaxStart</code> and to wrap the already bound success/error callbacks in another function which will allow me to modify the <code>options</code> object and thus the returned data.</p> <p>Below is the utility function that does the wrapping and an example:</p> <pre><code>var alterResponse = function (opts) { var callback = function (options, originalOptions, jqXHR) { if (options.url.match(opts.urlMatch)) { // Cache original callback. var originalSuccess = originalOptions.success || options.success; originalOptions.success = options.success = function () { // Call wrapper that will modify the response object. opts.successWrapper.call(null, options, originalOptions, jqXHR, originalSuccess); }; } }; if (opts.dataTypes) { $.ajaxPrefilter(opts.dataTypes, callback) } else { $.ajaxPrefilter(callback); } }; alterResponse({ urlMatch: /myurl/g, // Filter urls you what to tamper with. successWrapper: function (options, originalOptions, jqXHR, originalFn) { options.data.customVar = 'customValue'; originalFn(options, originalOptions, jqXHR); } }); </code></pre> <p>I have to mention i'm using this for testing purposes so i'm not concerned about performance, memory and overhead.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload