0

I'm making a game and to use it, you must register. So I'm trying to append a username and password that has been entered into a form to my JSON file which looks like:

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

My PHP reads:

<?php

    $username = $_POST['username'];
    $password = $_POST['password'];

    $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
    array_push($json, $username, $password);
    $jsonData = json_encode($json);
    file_put_contents('logins.json', json_encode($json));

?>

AJAX:

function callAJAX(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange=function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {                     
                    console.log(xhttp.responseText);

                    document.getElementById("PHPid").innerHTML = xhttp.responseText;
                }
            }
            xhttp.open("POST", "reg.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
        }

HTML:

<fieldset>
        <legend>Please register 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>
<div id="PHPid"><div>

<script>
var usernamePassed = '';
var userPassword = "";

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

        }
        function callAJAX(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange=function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                   console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
                }
            }
            xhttp.open("POST", "reg.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("username=" + usernamePassed + "&password="+ userPassword);

</script>

So for example if I inputted username: mike, password:123 into the HTML field it should update my json file but my json file is not changing.

I'm running it on localhost and I have checked the permissions, which are set to read and write for all users.

Any ideas why?

Thanks in advance

Michael Heneghan
  • 297
  • 1
  • 3
  • 13
  • worked fine for me. You sure those POST arrays have values? Use error reporting http://php.net/manual/en/function.error-reporting.php - You also tagged as ajax but nothing to support the question, should it be ajax related. If it is, look at your console. – Funk Forty Niner Apr 23 '16 at 14:58
  • That */ is not actually in my code, I've put that in this post by accident. Either way when I remove it, my Json file is still not getting updated – Michael Heneghan Apr 23 '16 at 15:09
  • remove it from the question then, because I closed the question based solely on it and from what I tested it with. Do check for errors as I stated originally. My tests were conclusive. – Funk Forty Niner Apr 23 '16 at 15:10
  • Where does the `*/` come from? – Muntashir Akon Apr 23 '16 at 15:11
  • Hey Fred, it's just cause the info is passed to PHP via an AJAX call, I've now included my AJAX code. Muntashir, that was an error of mine when entering my code onto stack overflow, they don't appear in my actual code – Michael Heneghan Apr 23 '16 at 15:16
  • Thanks Fred, I've just updated my question to include the HTML – Michael Heneghan Apr 23 '16 at 15:21
  • I've just added it. Directly below the input field. – Michael Heneghan Apr 23 '16 at 15:27
  • @MichaelHeneghan Ok, I didn't see it because you didn't indent it. Now, the JS that's below `
    `, is that not wrapped inside `` tags? I'm a bit baffled at this point. I'd have to set this all up and test it on my side. I'll see what I can do, but can't promise anything. JS isn't my bag *lol*
    – Funk Forty Niner Apr 23 '16 at 15:30
  • Cheers Fred, I've included the script tags now. – Michael Heneghan Apr 23 '16 at 15:34
  • @MichaelHeneghan I found the problem and have posted my answer below which I tested with your full code. – Funk Forty Niner Apr 23 '16 at 15:39

1 Answers1

0

The problem here is that you are missing a closing brace } for your callAJAX() function.

Having looked at your developer console, you would have seen the following:

SyntaxError: missing } after function body

Fixed script code:

<script>
var usernamePassed = '';
var userPassword = "";

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

        }
        function callAJAX(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange=function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                   console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
                }
            }
            xhttp.open("POST", "reg.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("username=" + usernamePassed + "&password="+ userPassword);

}

</script>

- Using a code editor with bracket/brace matching, would have helped ;-)

You are already using one as pointed out in comments.


What I tested this with was:

<fieldset>
        <legend>Please register 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>
<div id="PHPid"><div>

<script>
var usernamePassed = '';
var userPassword = "";

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

        }
        function callAJAX(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange=function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                   console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
                }
            }
            xhttp.open("POST", "reg.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
</script>

and

<?php

    $username = $_POST['username'];
    $password = $_POST['password'];

    $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
    array_push($json, $username, $password);
    $jsonData = json_encode($json);
    file_put_contents('logins.json', json_encode($json));

?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • It's just above the script tag – Michael Heneghan Apr 23 '16 at 15:45
  • No parse error on mine and they all seem to marry up fine. – Michael Heneghan Apr 23 '16 at 15:46
  • I'm using Sublime, the only thing appearing in the console is the print from checkLogin() function – Michael Heneghan Apr 23 '16 at 15:48
  • @MichaelHeneghan My editor shows that `function callAJAX(){` is unclosed. – Funk Forty Niner Apr 23 '16 at 15:49
  • 1
    @MichaelHeneghan *"It's just above the script tag"* - what do you mean by that? – Funk Forty Niner Apr 23 '16 at 15:50
  • I just added one to check and then it gave me a parse error. The closing brace was just above the script tag in my question above, it's not inline with the rest of the code. – Michael Heneghan Apr 23 '16 at 15:51
  • @MichaelHeneghan I copied your code from what you posted under **HTML:** and not what you pasted above that which does have the matching brace, so you may not have copied something correctly somewhere. I tested this on my own machine and it worked fine. Make sure you're not falling victim to caching. There isn't anything else I can do here Michael, sorry. My further tests were conclusive and did successfully write to the file. Make sure both folder and the file have write permissions. Copy what I have in my answer exactly as shown. – Funk Forty Niner Apr 23 '16 at 15:53
  • Thanks for your efforts Fred, I've just double check all permissions etc and all ok but not working. I've checked yours as the correct answer as it must be something on my machine. How do I check against caching?? – Michael Heneghan Apr 23 '16 at 15:59
  • @MichaelHeneghan You're welcome Michael. Have you tried error reporting and/or logs? Use `var_dump();` to see what's going through or not. TBH, I always like to have things completely resolved ;-) – Funk Forty Niner Apr 23 '16 at 16:02