-2

How can this be done without JQuery?

Here is my code:

function runScript(params) {
xhr = new XMLHttpRequest();
xhr.open('POST', 'scripts.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200) {
        document.getElementById("dynamic").innerHTML = xhr.responseText;
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(encodeURI(params));
}

I would like something like this:

xhr.finished {
    alert(AJAX has finished it's process and the HTML has been updated);
}
  • You'd have to do what jQuery does, register a `onreadystatechange` callback. https://developer.mozilla.org/de/docs/Web/API/XMLHttpRequest – Thilo Jan 15 '17 at 23:41
  • What does `onload` do? Who provides that? – Thilo Jan 15 '17 at 23:43
  • Bring on the `fetch` API -- this will all be so much nicer... – lonesomeday Jan 15 '17 at 23:51
  • `onreadystatechange` is so last decade ... you are using `onload`, which is the correct event to listen for as it triggers when load is successful (yes, even a 404 is successful) ... alternatively, there's an `onloadend` which triggers on any of the "end events" i.e., load, error or abort – Jaromanda X Jan 16 '17 at 00:18

1 Answers1

0

You're attaching the wrong event handler... try onreadystatechange. For your case, I would recommend adding in a callback function to your runScript function:

function runScript(params, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'scripts.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function () {
        if(xhr.readyState === XMLHttpRequest.DONE) {
            callback(xhr.status, xhr.responseText);
        }
    };
    xhr.send(encodeURI(params));
}

runScript('foo=bar', function finished(status, response) {
    console.log('It is done...');
});
Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55
  • onreadystatechange is so last decade ... loadstart, progress, load, timeout, error, abort, loadend events are the way to use XHR since 2008 at least – Jaromanda X Jan 16 '17 at 00:21