cmplieger
cmplieger

Reputation: 7361

Append HTML doc to element using ajax

I've written this code using various online sources but I cannot seem to figure out the last part.

function loadajax (event) {
    event.preventDefault();
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange  = function(){ 
        if(xhr.readyState  == 4){
            if(xhr.status  == 200) 
                document.ajax.dyn="Received:"  + xhr.responseText; 
            else
                document.ajax.dyn="Error code " + xhr.status;
        }
    }; 

    xhr.open('GET', this.href, true);
    var content = document.getElementsByTagName('article')[0];

    content.innerHTML = xhr.responseText;
}

It seems to work until I need to add content to my page. Indeed content.innerHTML = xhr.responseText; returns nothing. I am getting a simple HTML file, how can I post it in my page? what am I doing wrong?

Thanks for your help!

Upvotes: 0

Views: 141

Answers (2)

CD..
CD..

Reputation: 74166

ajax calls are asynchronous. it will work if you'll move the content.innerHTML = xhr.responseText; line into the onreadystatechange function like this:

function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
 xhr.onreadystatechange  = function() 
    { 
       if(xhr.readyState  == 4)
       {
        if(xhr.status  == 200) 
            document.ajax.dyn="Received:"  + xhr.responseText; 

            content.innerHTML = xhr.responseText;
        else
            document.ajax.dyn="Error code " + xhr.status;
        }
    }; 

xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];

}

Upvotes: 3

Diego ZoracKy
Diego ZoracKy

Reputation: 2285

Put your contet.innerHTML inside status 200 condition.

You are just assigning the value to content before it really exists. Before the ajax got it from server.

Upvotes: 1

Related Questions