How to check if onreadystatechange returns error with Javascript?

So I have a JSON API that I put a variable in at the end, and if the variable is a "valid" username (if the account actually exists) it will return information about it, but if the account isn't valid/doesn't exist it returns {} and in the console of the website I'm accessing the API with it shows an error saying

Uncaught TypeError: Cannot read property 'steamID' of undefined
    at XMLHttpRequest.profileCheck.onreadystatechange

So I was wondering how I can check if that error is returned with an if statement? For example something like if(typeError === true) { do code } else { something else};

Here's the code I'm using to access the API (if that's important at all):

function isID64() {

    var id64 = document.getElementById("username").value;

    var realID64;

    var profileCheck = new XMLHttpRequest;"GET", "<api im using>" + id64);

    profileCheck.onreadystatechange = function() {
        if (profileCheck.readyState === 4) {

            var profileCheckResponse = JSON.parse(profileCheck.responseText);

            realID64 = profileCheckResponse.playerstats.steamID;




Any help is appreciated :)

Answers 1

  • I think this type error is because you are using JSON file to send data from your back end (php or something). if user is not exist it sends either null or a string. but in front end JSON.parse statement expect an json variable. Do following thing in your back end

    if(userexist()) //save data into json variable; else //save "User Not exist" into your json variable.

    then change your code from frontend (Javascript)

    if (profileCheck.readyState === 4) 
     var profileCheckResponse = JSON.parse(profileCheck.responseText);
     if(profileCheckResponse[0]=="User Not Exist";
     //Display Error 
      realID64 = profileCheckResponse.playerstats.steamID;

Related Articles