Hi everyone.
I’m developing a website and I want only use javascript, I don’t want add jquery to use json functions, so… I’m using the native functions of javascript to work with json, basically I need help to make the same function of jquery, using only the native functions.
In jquery I have the following function that works fine, but when I make the same function only using javascript it doesn’t work. Anyone can tell me what’s wrong?
Javascript example
var channels = ['maddenamy', 'other_channel', 'etc'];
for(i = 0;i < channels.length;++i){
var xmlhttp = new XMLHttpRequest(),
url = 'https://api.twitch.tv/kraken/channels/'+channels[i];
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
document.getElementById('names').innerHTML += myArr.display_name; // it loads the channels like jquery .append function
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
The jquery example returns all the channels, but the javascript example returns only the last channel.
it has to do with asynchronous calculation working better with recursion
Not exactly. The issue has to do with scope.
You reference xmlhttp inside your callback function (onreadystatechange), but then overwrite xmlhttp with your loop before the callback can fire. Therefore you’re always checking against the last channel in the array.
By making it recursive you introduce a closure which isolates the scope and prevents the reference to xmlhttp from being overwritten. Alternatively, you can just change references from xmlhttp to this and it’ll also work.
var channels = ['maddenamy', 'other_channel', 'etc'];
for(i = 0;i < channels.length;++i){
var xmlhttp = new XMLHttpRequest(),
url = 'https://api.twitch.tv/kraken/channels/'+channels[i];
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
document.getElementById('names').innerHTML += myArr.display_name; // it loads the channels like jquery .append function
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}