I need a pure JavaScript function (Sorry, no jQuery) that will return the response from a successful AJAX call. Here's the function I've got so far, I want to return the HTMLobject
with the HTML from the response:
function getHtml(url) {
var httpRequest;
var HTMLobject;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!httpRequest) {
console.error('Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
// OK, turn the string into HTML.
var div = document.createElement('div');
div.innerHTML = httpRequest.responseText;
// Assign the converted HTML to HTMLobject.
HTMLobject = div.childNodes[0];
} else {
console.debug('There was a problem with the request.');
}
}
};
httpRequest.open('GET', url);
httpRequest.send();
return HTMLobject;
}
I know why, HTMLobject
returns undefined, but I need it to work. Is there a way to have the function return the object after the AJAX has completed?