I want to create a simplified, reusable Ajax function for my project. After wrapping XMLHttpRequest into a function, I cannot return a response object. The response object can only be printed with console.log(obj). return obj returns undefined instead of returning an object. What am I doing wrong?
function xhr(xhrObject) {
let xhr = new XMLHttpRequest();
xhr.open(xhrObject.type, xhrObject.destination, true);
xhr.getResponseHeader("Content-type", "application/json");
xhr.responseType = xhrObject.response;
xhr.onreadystatechange = function () {
if(this.readyState === 4 && this.status === 200) {
let obj = xhr.response;
console.log(obj);
//return obj; instead of returning objects, it returns undefined
}
};
// Send request
let json = JSON.stringify(xhrObject.data);
xhr.send(json);
}
To use a function I pass an object to it.
let object = {
type: 'POST',
destination: 'request.php',
selector: '.result',
data: {a: "a", b: "b", c: "c"},
response: 'json' // text, json
};
xhr(object);
Thanks to solution here now I can get the response object.
Change
return xhr.response;
to
callback(xhr.response);
And now call function like this
xhr(object, function(result) {
// now result will return and object, object values can be accessed like this:
alert(result.Name);
});
My last question is: Is there any possible optimization for this? Or the final result is good enough and nothing else should be done?