JSFiddle - React, Tailwind, and code Playground

by _nderscore

HTML

<input type="submit" value="Do AJAX" />
<div id="testElement">
    This is the test element which will be updated by ajax.
</div>

JavaScript

/* shim */
_core = window._core || {};
/* /shim */

/* _core AJAX listeners
 * 
 * _core.addPreAjaxListener
 * _core.addPostAjaxListener
 *
 * match = url, accepts string or regex
 * func  = function to execute
 */
(function(){
    if(_core._preAjaxListeners) return;

    _core._preAjaxListeners = [];
    _core._postAjaxListeners = [];
    _core._fireAjaxEvents = function(flag, href){
        if (!href) return;
        var arr;
        if (flag == 'pre') 
            arr = _core._preAjaxListeners;
        else if (flag == 'post') 
            arr = _core._postAjaxListeners;
        else return;
        for(var i = 0, l = arr.length; i < l; i++){
            var x = arr[i];
            if(typeof x.match == 'string' && href == x.match)
                x.handler();
            else if (x.match.test && x.match.test(href))
                x.handler();
        }
    };

    _core.addPreAjaxListener = function(match, handler){
        _core._preAjaxListeners.push({ match: match, handler: handler });
    };

    _core.addPostAjaxListener = function(match, handler){
        _core._postAjaxListeners.push({ match: match, handler: handler });
    };

    XMLHttpRequest.prototype.open = (function(orig){
        return function(a,b,c){
            this._HREF = b;
            return orig.apply(this, arguments);
        };
    })(XMLHttpRequest.prototype.open);

    XMLHttpRequest.prototype.send = (function(orig){
        return function(){
            var xhr = this;
            _core._fireAjaxEvents('pre', xhr._HREF);
            console.log('href is', xhr._HREF);
            
            var rsc = xhr.onreadystatechange || function(){};
            xhr.onreadystatechange = function(){
                try {
                    if (xhr.readyState == 4){
                        _core._fireAjaxEvents('post', xhr._HREF);
                        this.onreadystatechange = rsc;
                    } 
                } catch (e){ }
                return rsc.apply(this, arguments);
  ...