Update html based on if stream is live


#1

This is what I have so far:

<body>
<p id="content"></p>
</body>
<script>

var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Client-ID", "my client id");
window.onload = xhr.open("GET", "https://api.twitch.tv/helix/streams?user_login=dakotaz", false);
var data = JSON.parse(xhr.responseText);
content = <p>data</p>
</script>

This does not update the body section so it must be an issue with how I am handling the api


#2

What errors do you get in your inspector/console?

And it would appear your have totally misconstrued the XMLHttpRequest

https://javascript.info/xmlhttprequest

You probably want something more like

<script>
window.onload = function() {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.twitch.tv/helix/streams?user_login=dakotaz');
    xhr.setRequestHeader("Client-ID", "my client id");
    xhr.send();
    xhr.onload = function() {
        if (xhr.status != 200) {
            console.log('Handle non 200');
        } else {
            var data = JSON.parse(xhr.responseText);
            if (data && data.data[0]) {
                //live
            } else {
                //not live
            }
        }
    }
}
</script>

#3

Nothing is showing in the console, I’ve just tried this code and the body is still not updating.

window.onload = function() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.twitch.tv/helix/streams?user_login=dakotaz', true);
xhr.setRequestHeader("Client-ID", "my client id");
xhr.send();
xhr.onload = function() {
    if (xhr.status != 200) {
        console.log('Handle non 200');
    } else {
        var data = JSON.parse(xhr.responseText);
        if (data && data.data[0]) {
            content = <p>Online</p>
        } else {
            content = <p>Offline</p>
        }
    }
}
}

#4
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.twitch.tv/helix/streams?user_login=dakotaz', true);
xhr.setRequestHeader("Client-ID", "A Valid Client ID");
xhr.send();
xhr.onload = function() {
    if (xhr.status != 200) {
        console.log('Handle non 200');
    } else {
        var data = JSON.parse(xhr.responseText);
        if (data && data.data[0]) {
            content = '<p>Online</p>'
        } else {
            content = '<p>Offline</p>'
        }
console.log(content);
    }
}

Works for me