Michael Heneghan
Michael Heneghan

Reputation: 307

loop through JSON file using ajax, PHP & Javascript

I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.

Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:

JSON:

{"LogIns":[
   {
    "Username":"mikehene",
    "password":"123"
   },
   {
    "Username":"mike",
    "password":"123"
   }
]
}

HTML:

<fieldset>
    <legend>Please log in before playing</legend>
    <form>
        Username: <br>
        <input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
        Password: <br>
        <input type="password" placeholder="Enter a password" id="password" name="password"><br>
        <input type="submit" value="Submit" onclick="return checkLogin();">
    </form>
</fieldset>

PHP:

<?php

$username = $_POST['username'];

$str = file_get_contents('logins.json'); // Save contents of file into a variable

$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json

echo json_encode($json);

?>

Javascript & AJAX call:

var usernamePassed = '';

function checkLogin(){
    usernamePassed = document.getElementById("username1").value;
    callAJAX();
    return false;

}

function callAJAX(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange=function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            myFunction(xhttp.responseText);
        }
    }
    xhttp.open("POST", "LogInReg.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("username=" + usernamePassed);
}


function myFunction(response) {

    var arr = response;
    var objJSON = JSON.parse(arr);
    var len = objJSON.length;

    for(var key in objJSON){
        console.log(key);
    }
}

But it only prints out "LogIns". I also tried this:

for (var i = 0; i < objJSON.length; ++i) {
                 if(objJSON[0].Username == usernamePassed){
                    console.log("found it");
                 }
                 else{
                    console.log("didn't find it!");
                 }
            }   

Therefore I tried another approach (parse the data in the PHP file) like so:

foreach ($json['LogIns'][0] as $field => $value) {
        if($json['LogIns'][0]['Username'] == $username){
            echo "Logged In";
               break;
            }
            else{
                echo "No user found";
                break;
            }
        }

But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).

Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.

I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.

Any help would be GREATLY appreciated.

Thanks in advance

Upvotes: 0

Views: 353

Answers (1)

Sachin Vairagi
Sachin Vairagi

Reputation: 5334

Try this

 $json = json_decode($str, true);
 $password = $_POST['password'];

        foreach($json['LogIns'] as $res)
        {
            if($res['Username']==$username && $res['password']==$password)
            {
                echo json_encode($res['Username']);
               //echo 'user found'; 
            }
        }

Upvotes: 1

Related Questions