Promise executing before json php file loads and get 500 internal server error

Promise executing before json php file loads and get 500 internal server error
0

#1

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 is the nameTaken function that’s in a different directory and file. 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. -

`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?


#2

You’ve added the event listener on the submit itself, so the promise will kick off at the same time as the form submit and the promise resolves on the same page before the redirect to your “/” page.

You could use a jQuery ajax call for the initial form submit and handle what you do in the promise in the success handler for the ajax call (if you’re using jQuery), then decide how you want to present a result to the user. That’s be one way.

As far as the network and console logs clearing after each new request, in Google Chrome, you can preserve those as indicated in the attached images, so you can check the separate requests.

2018-08-17_15-18-28