0

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?

Grufas
  • 1,350
  • 4
  • 21
  • 33
  • 1
    Why not read about [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) instead ? – Louys Patrice Bessette Dec 04 '22 at 08:14
  • 1
    Yeah, I suggest using `fetch`, look into the concept of Promises/async-await (see [this answer](https://stackoverflow.com/a/14220323/5648954) for an intro), it'll help you with dealing with sort of issue (see [this answer](https://stackoverflow.com/a/59916857/5648954) for an approach using `fetch`) – Nick Parsons Dec 04 '22 at 08:18
  • fetch was my second option to try, but I don't want to jump on other method without solving this one, so I want to figure out how to return object. – Grufas Dec 04 '22 at 08:21

0 Answers0