Remove jQuery dependency for AJAX call/load
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I want to load content on the pen linked to below without using jQuery. I need someone to rewrite the Javascript to remove the jQuery dependency.

http://codepen.io/garyrozanc/pen/jqyOEB

awarded to Artem Shavrin

Crowdsource coding tasks.

3 Solutions

Winning solution

Something like this? Demo: http://codepen.io/anon/pen/BKpyam

document.addEventListener('DOMContentLoaded', function() {
    var collapse1 = document.querySelectorAll('#collapse-1')[0];
    collapse1.addEventListener('click', function() {
        ajaxLoad('#collapse-1-content', 'http://codepen.io/garyrozanc/pen/xVgxWe.html #collapse-1');
    });
    var collapse2 = document.querySelectorAll('#collapse-2')[0];
    collapse2.addEventListener('click', function() {
        ajaxLoad('#collapse-2-content', 'http://codepen.io/garyrozanc/pen/xVgxWe.html #collapse-2');
    });
    var collapse3 = document.querySelectorAll('#collapse-3')[0];
    collapse3.addEventListener('click', function() {
        ajaxLoad('#collapse-3-content', 'http://codepen.io/garyrozanc/pen/xVgxWe.html #collapse-3');
    });
});


function ajaxLoad(elementSelector, urlWithSelector) {
    var domElement = document.querySelectorAll(elementSelector)[0];

    var urlParts = urlWithSelector.split(' ');

    var request = new XMLHttpRequest();
    request.open('GET', urlParts[0], true);
    request.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (this.status >= 200 && this.status < 400) {
                var node = document.createElement('div');
                node.innerHTML = this.responseText;
                if (urlParts.length > 1) {
                    var el = node.querySelector(urlParts.slice(1).join(' '));
                    if (el !== null) {
                        domElement.innerHTML = el.innerHTML;
                    }
                } else {
                    domElement.innerHTML = this.responseText;
                }
            } else {
                // do something with error
            }
        }
    };

    request.send();
    request = null;
}
Works perfectly!
imokyourok over 4 years ago

var url_base = "http://codepen.io/garyrozanc/pen/xVgxWe.html#collapse-";

document.getElementById("collapse-1").addEventListener("click", loadAjax);
document.getElementById("collapse-2").addEventListener("click", loadAjax);
document.getElementById("collapse-3").addEventListener("click", loadAjax);

function loadAjax() {
var elementId = this.id;
var panelNum = elementId.substring(elementId.length-1);
var req = new XMLHttpRequest();
req.open("GET", url_base + panelNum, true);
req.onreadystatechange = function () {
if (req.readyState != 4 || req.status != 200)
return;

document.getElementById(elementId + "-content").innerHTML = req.responseText;
};
req.send("");
}


/*! @source https://gist.github.com/1129031 */  
/*global document, DOMParser*/
(function(DOMParser) {  
    "use strict";  
    var DOMParser_proto = DOMParser.prototype  
      , real_parseFromString = DOMParser_proto.parseFromString;

    // Firefox/Opera/IE throw errors on unsupported types  
    try {  
        // WebKit returns null on unsupported types  
        if ((new DOMParser).parseFromString("", "text/html")) {  
            // text/html parsing is natively supported  
            return;  
        }  
    } catch (ex) {}  

    DOMParser_proto.parseFromString = function(markup, type) {  
        if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {  
            var doc = document.implementation.createHTMLDocument("")
              , doc_elt = doc.documentElement
              , first_elt;

            doc_elt.innerHTML = markup;
            first_elt = doc_elt.firstElementChild;

            if (doc_elt.childElementCount === 1
                && first_elt.localName.toLowerCase() === "html") {  
                doc.replaceChild(first_elt, doc_elt);  
            }  

            return doc;  
        } else {  
            return real_parseFromString.apply(this, arguments);  
        }  
    };  
}(DOMParser));


function loadContentAjax(url, localId, remoteId) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if(xmlhttp.status == 200){
                console.log('here');
                console.log(xmlhttp.responseText);
                var container = document.getElementById(localId);
                var parser = new DOMParser();
                dom = parser.parseFromString (xmlhttp.responseText, "text/html");
                container.innerHTML = dom.getElementById(remoteId).innerHTML;
           }
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

window.onload = function(){
    var collapse1 = document.getElementById("collapse-1");
    var collapse2 = document.getElementById("collapse-2");
    var collapse3 = document.getElementById("collapse-3");
    var url = 'http://codepen.io/garyrozanc/pen/xVgxWe.html';

    collapse1.addEventListener('click', function(){
        loadContentAjax(url, 'collapse-1-content', 'collapse-1');
    });

    collapse2.addEventListener('click', function(){
        loadContentAjax(url, 'collapse-2-content', 'collapse-2');
    });

    collapse3.addEventListener('click', function(){
        loadContentAjax(url, 'collapse-3-content', 'collapse-3');
    });
}
View Timeline