Arthur A. Bergamaschi
Arthur A. Bergamaschi

Reputation: 125

XMLHttpRequest readyState stops on 1

I'm having some problems with this code I've done:

function server_status() {
    setInterval(function(){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://mcapi.sweetcode.de/api/v2/?info&ip=jogar.millenarycraft.com', true);
        xhr.onreadystatechange = new function(){
            document.getElementById("server_counter").innerHTML = 'ReadyState: ' + xhr.readyState;
            if (xhr.readyState == 4) {
                data = JSON.parse(xhr.responseText);
                if(data.status){
                    document.getElementById("server_counter").innerHTML = '<span>Jogadores online: <span style="color:#FD7C00;">' + data.player.online + '</span></span>';
                }else{
                    document.getElementById("server_counter").innerHTML = '<span style="color:#FD7C00;">Servidor offline!</span>';
                }
            }
        }
        xhr.send();
    }, 1000);
}

It is inside a script tag and work as well, but I'm having problems just from document.getElementById("server_counter").innerHTML = 'ReadyState: ' + xhr.readyState; on. I noticed that the readystate stops on 1 and I don't know why! Can anyone help me?

PS: And the problem is not with the url, because I did a PHP version and it worked very well. I just want to use JavaScript because I need to update the value without refreshing the page in a certain time.

Upvotes: 0

Views: 464

Answers (1)

Halcyon
Halcyon

Reputation: 57728

I think you have an unintended error:

xhr.onreadystatechange = new function(){

Change to:

xhr.onreadystatechange = function(){

new should most certainly not be there. I think as it is your function is called once before you've called xhr.send(), hence xhr.readyState is 1.

Upvotes: 2

Related Questions