0

I made a PHP function that echo's JSON after a form is submitted and I want to interact with that with a promise request. I keep getting a 500 internal server error and I don't know why.

Here are my files - this is registerFail.js that's supposed to get the JSON after the form is submitted so I can alert a message, it's in the main directory :

window.onload = function(){

    function get(url) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.onload = () => resolve(xhr.responseText);
          xhr.onerror = () => reject(xhr.statusText);
          xhr.send();
        });
      }

    document.getElementById('register').addEventListener('submit', () => {
            let promise = get('/controllers/add-user.php').then((name) => {
            console.log(name);
        });
    });
}

This is my controller php class in the directory /controllers/add-user.php, and it is where the promise in registerFail.js is supposed to get the json from

header('Content-type: text/javascript');

$hash = password_hash($_POST['password'], PASSWORD_BCRYPT);

if(!$app['database']->nameTaken($_POST['username'])){

    $app['database']->insert('users', [

        'name' => $_POST['username'],

        'password' => $hash

    ]);
};

header('Location: /'); 

the ->nameTaken function is what echo's the JSON.

Here are the nameTaken function that's in a different directory and file -

public function nameTaken($username){

        $statement = $this->pdo->prepare('SELECT count(*) FROM users WHERE name = :name');

        $statement->execute(array('name' => $username));

        $res = $statement->fetch(PDO::FETCH_NUM);

        $exists = array_pop($res);

        if ($exists > 0) {

            $json = array(
                'success' => false
            );

            echo json_encode($json);

            return true;

        } else {
            //the name can be made
            return false;
        }
    }

In my server I'm getting these messages :

[Thu Aug 16 12:16:18 2018] 127.0.0.1:44906 [200]: /
[Thu Aug 16 12:16:18 2018] 127.0.0.1:44910 [200]: /registerFail.js
[Thu Aug 16 12:16:22 2018] PHP Notice:  Undefined index: password in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 5
[Thu Aug 16 12:16:22 2018] PHP Notice:  Undefined variable: app in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7
[Thu Aug 16 12:16:22 2018] PHP Fatal error:  Uncaught Error: Call to a member function nameTaken() on null in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php:7
Stack trace:
#0 {main}
  thrown in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7
[Thu Aug 16 12:16:22 2018] 127.0.0.1:44996 [500]: /controllers/add-user.php - Uncaught Error: Call to a member function nameTaken() on null in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php:7
Stack trace:
#0 {main}
  thrown in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7
 [Thu Aug 16 12:16:22 2018] 127.0.0.1:45000 [200]: /users

It looks like my promise is executing and trying to get the json before the php file has loaded so none of the json is there and I'm getting these errors for undefine variables. I see the 500 error for a split second before the /users ( /controllers/add-user.php) php json file is loaded and see all those errors above in my server, but then when the php file has loaded the post from the form, it all works properly and I see the correct json, but when I'm redirected back to the '/' main file, the console is cleared and my promise does not console.log the json.

So I think my problem is that the promise executes immediately after my the submit button is clicked on, but I need it to execute after the php json file has loaded so I don't get the 500 server error in my console and the server errors from my terminal shown above.

How can I get my promise to execute after the php file has loaded and I'm redirected back to the '/' page?

icewizard
  • 133
  • 1
  • 13
  • 1
    `500` error code is the server issue. please check your server-side code again. – Khoa TruongDinh Aug 16 '18 at 02:48
  • 1
    "I keep getting a 500 internal server error and I don't know why" - Time to look at your server's error log file or [turn on error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). – Mike Aug 16 '18 at 03:02
  • Why? use ```echo json_encode($json);``` in ```public function nameTaken($username){``` – hamed hossani Aug 16 '18 at 05:01
  • Did you try opening `/users` in your browser? – Domenik Reitzner Aug 16 '18 at 15:47
  • Yes, the /users page is working and showing the correct output. I just updated my question with more information and I think I found the problem but I don't know how to solve it. I appreciate the help. – icewizard Aug 16 '18 at 16:24
  • 1
    @hamedhossani The function was made to check if a name is already in my database. if a name is arleady there, the function returns false and I echo the json so for my promise, so that I can make an alert of stylish html to show the user that the name is taken. Should I have put it somewhere else? – icewizard Aug 16 '18 at 16:31
  • 1
    In picture log of server."Undefined index: password " what's? are you send password parameter? In line 3 – hamed hossani Aug 16 '18 at 17:21
  • @hamedhossani $_POST['password'] and then I hash it. It all works fine though when the php file is loaded. The problem is that I'm getting these errors because the promise get request is executing to the php json file before that file has gotten the $_POST['password'] and other parameters so it returns everything undefined. The php file has to load first and then I need to send the promise get request, but I don't know how to do this. – icewizard Aug 16 '18 at 17:35
  • @icewizard But you don't send the `username` and `password` parameters thought the ajax call! – Chayim Friedman Aug 17 '18 at 06:15

1 Answers1

0

I just discovered sesssions and using them worked. Here is my code in add-user.php

<?php

session_start();

$hash = password_hash($_POST['password'], PASSWORD_BCRYPT);

if(!$app['database']->nameTaken($_POST['username'])){

    $app['database']->insert('users', [

        'name' => $_POST['username'],

        'password' => $hash

    ]);
} else {
    $_SESSION['error'] = 'Username is taken';
}

header("location:/");

Then I made the session equal to a variable in my controller class for the page with my form

session_start();

$error = $_SESSION['error'];

and then I made an if statement in my form page to show the $error variable if its set, then unset the session and its working how I want it to.

icewizard
  • 133
  • 1
  • 13