2016-04-23 10:49
浏览 83


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:




    <legend>Please log in before playing</legend>
        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();">



$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;
    return false;


function callAJAX(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange=function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
    }"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){

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");
                    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";
                echo "No user found";

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题