brunobliss
brunobliss

Reputation: 366

why are ajax asynchronous calls not changing the innerHTML of elements?

PLan is simple, get a couple of <li> from the data.txt. This works when i use the synchronous method (false) and does not when i use the default true, here's the code that

WORKS:

function change() {
    var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    ajax.open('GET','data.txt',false);
    ajax.send();
    var changeME = document.getElementById('changeMe');
    changeME.innerHTML = ajax.responseText;
}

DOES NOT WORK

function change() {
    var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    ajax.open('GET','data.txt',true);
    ajax.send();
    var changeME = document.getElementById('changeMe');
    changeME.innerHTML = ajax.responseText;
}

the HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
    </head>
    <body>
        <div id="changeMe"> </div>
        <input type="button" id="lol" onclick="change();" value="Change" />
    </body>
    <script src="script.js"></script>
</html>

the DATA.TXT

<li>List item 1</li>
<li>List item 2</li>

Upvotes: 0

Views: 335

Answers (1)

Slippery Pete
Slippery Pete

Reputation: 3110

You need to set a handler for when the async call completes, and do your DOM updates there:

function change() {
    var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            var changeME = document.getElementById('changeMe');
            changeME.innerHTML = ajax.responseText;
        }
    }
    ajax.open('GET', 'data.txt', true);
    ajax.send();
}

Upvotes: 3

Related Questions