Interactive by Nature

AJAX without jQuery

Wednesday, December 12th, 2012

I like to post about problems that I solve so that I can refer back to if I ever encounter the same problem in the future. This time I needed to make an AJAX request without using jQuery. I’ll be honest… I’ve ALWAYS used jQuery for AJAX. Why wouldn’t you? It’s so easy, plus if you’re already using jQuery, it’s more efficient. I didn’t know where to start, but after some research, I came up with the following:

$('#container').on('tap', '#element', function(event) {
	
    //GET URL FROM TAPPED ELEMENT
    var requestURL = $(this).attr('href');
		
    var xmlhttp = null;
    
    if (window.XMLHttpRequest) {
        //IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp = new XMLHttpRequest();
    }
		
    xmlhttp.open('GET',requestURL,true);
    //XMLHttpRequest - I GUARANTEE IT!
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 
    xmlhttp.send(null);

    xmlhttp.onreadystatechange = function() {
	if (xmlhttp.readyState==4 && xmlhttp.status==200) {		
	    document.getElementById('container').innerHTML=xmlhttp.responseText;

	}
    }

    //PREVENT DEFAULT BUTTON BEHAVIOR
    event.preventDefault();
	
});

As you can probably see, I AM indeed using jQuery for the tap event and URL gathering. The jQuery version that this post references is v1.7.1. using the .on() method; the rest is old school javascript. Let’s break it down!

(more…)

Posted in Code, Development, jQuery, Mobile | No Comments »