Home > database >  javascript json object value returns undefined
javascript json object value returns undefined

Time:02-22

I realize there are 100's of posts about javascript json objects. And all of them imply my code should work, so I am sure I am missing something really stupid. Every attempt to access the json object's key value results in undefined even though the json.parse works fine.

var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
            var resp = JSON.parse(this.responseText);
            alert(this.responseText);
            alert(resp.toString());
            alert(resp.exists);
            alert(resp['exists']);
            
         }
    };

This results in the following for alerts:

"{\"exists\":\"True\"}"
{"exists":"True"}
undefined
undefined

What incredibly obvious and dumb thing am I missing? I even attempted to use my exact string in w3schools example and it appears to work fine https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_dot

Thank you in advance.

CodePudding user response:

I don't know how it was working using your browser, I got a set of syntax errors when I was trying to test your code. Finally only this code was working

    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
            var resp = xhr.response;
            alert(JSON.stringify( resp)); //{"exists":"True"}
             alert(resp.exists); //"True"
            alert(resp['exists']); //"True"
          }
    };
    xhr.send();

but common way to use it

    xhr.onload = () => {
        resp= xhr.response;
    }
     xhr.onerror = () => {
        console.log("error "   xhr.status);
    }

CodePudding user response:

var resp = JSON.parse(this.responseText);

Here, change var to const because may be overide

  • Related