1

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?

igneosaur
  • 3,268
  • 3
  • 29
  • 44

2 Answers2

1

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).

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • This can produce unintended consequences like freezing up the UI on the page until the response returns, which in the case of a glitch or problem with the server or connection, could be a long time. – cazort May 11 '19 at 17:49