0

I have a login webpage, and I'm trying to use JavaScript to access a JSON file and check for the username and password. Though when I try to do it, it gives me an error.

I've tried to use an if statement to check whether the username and password is in the JSON data but that gives me an undefined error.

The login function is triggered when the submit button is clicked using onclick attribute. JavaScript:

<div id="input">
    <input type="text" id="i1" placeholder="Username" />
    <input type="password" id="i2" placeholder="Password" />
    <input type="submit" id="sm" value="Log In" onclick="login()">
    </div>
i1 = document.getElementById("i1"); //username
i2 = document.getElementById("i2"); //password
sm = document.getElementById("sm"); //submit 


function login() {
    $.getJSON("json/login.json", function(jsdata) {
        json = jsdata;
        user = i1.value;
        password = i2.value;

        if (json.user[password]){
            console.log("success")
        }
               
    })
}
TypeError: json.user is undefined

login.json:

{
    "potato48": "mypassword" 
}

I even tried another method:

JavaScript 2:

i1 = document.getElementById("i1"); //username
i2 = document.getElementById("i2"); //password
sm = document.getElementById("sm"); //submit 


function login() {
    $.getJSON("json/login.json", function(jsdata) {
        json = jsdata;
        user = i1.value;
        password = i2.value;
        if (user == json.user["username"] && password == json.user["password"]){
            console.log("success")
        }
               
    })
}

login.json 2:

i1 = document.getElementById("i1"); //username
i2 = document.getElementById("i2"); //password
sm = document.getElementById("sm"); //submit 


{
    "potato48": {
        "username": "potato48",
        "password": "pwd"
    }
    
}

It still gives me the same error.

potato
  • 79
  • 1
  • 11

1 Answers1

0

JSON is simply a string. JSON needs to be parsed in order to convert it to javascript object and then you'll be able to read the keys.

You can try something like this:

function login() {
    $.getJSON("json/login.json", function(jsdata) {
        json = JSON.parse(jsdata);
        user = i1.value;
        password = i2.value;

        if (json.user[password]){
            console.log("success")
        }
               
    })
}

Sachin Yadav
  • 128
  • 3
  • 12
  • It always gives me this error: `SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data` – potato May 23 '21 at 13:31
  • When I do `typeof(jsdata)` it says `Object` – potato May 23 '21 at 13:32
  • The error is probably coming from the part `if i1 == json.user["username"] && i2 == json.user["password"])` , I think it could be taking `user` as a string and not a variable – potato May 23 '21 at 13:34