Search code examples
javascriptxmlhttprequest

get data from XMLHttprequest


I want to get data in json format. I have typed this code but it doesn't return anything. where is the problem in my code?!!

<script language="JavaScript">
var xmlhttp = new XMLHttpRequest();

var url = "http://codeforces.com/api/contest.list?gym=true";


xmlhttp.onreadystatechange = myfunction;

xmlhttp.open("GET", url, true);

xmlhttp.send(null);


function myfunction() {

if (XMLHttp.readyState == 0) {
window.alert("Uninitialized");
}
if (XMLHttp.readyState == 1) {
window.alert("loading");
}
if (XMLHttp.readyState == 2) {
window.alert("loaded");
}
if (XMLHttp.readyState == 3) {
window.alert("waiting");
}
if (XMLHttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}


</script>

in the html code, i have a div with id = "id01"


Solution

  • remember that javascript is case sensitive.

    edit it to:

    var xmlhttp = new XMLHttpRequest();
    
    var url = "http://codeforces.com/api/contest.list?gym=true";
    
    
    xmlhttp.onreadystatechange = myfunction;
    
    xmlhttp.open("GET", url, true);
    
    xmlhttp.send(null);
    
    
    function myfunction() {
    
    if (xmlhttp.readyState == 0) {
    window.alert("Uninitialized");
    }
    if (xmlhttp.readyState == 1) {
    window.alert("loading");
    }
    if (xmlhttp.readyState == 2) {
    window.alert("loaded");
    }
    if (xmlhttp.readyState == 3) {
    window.alert("waiting");
    }
    if (xmlhttp.readyState == 4) {
    window.alert("completed");
    var y = JSON.parse(xmlhttp.responseText);
    document.getElementById("id01").innerHTML =y[1].id;
    }
    }