Reputation: 3346
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?
Upvotes: 1
Views: 1444
Reputation: 388416
No, the solution is such a case is to use a callback function.
Ex:
function getHtml(url, callback) {
....
....
callback(HTMLobject); //instead of returning the HTMLobject, call a callback function as pass the `HTMLobject` as a argument.
}
Usage:
getHtml('url', function(HTMLobject){
//Do something with HTMLobject
});
instead of
var HTMLobject = getHtml('url');
//Do something with HTMLobject
Making a request async: false
is a bad idea since it will block the page till the request is completed(UI will not get redrawn and ui interaction will not happen).
Upvotes: 1
Reputation: 176946
make request synchronous , just by doing as below
httpRequest.open('GET', url,false);//false make request synchronous
httpRequest.send();
The "false" option says the call is synchronous, meaning that the code will hang until a response comes back
Upvotes: 1