dsxpt62448 2018-08-16 23:59
浏览 66

提交表单发表后,如果只能通过帖子访问文件,如何发送消息到html / javascript? 发布请求

I'm trying to make my registration form show a message, on the same page as the registration form, that a username is taken if it is taken after the form is submitted.

I made a registration form that posts input to the file add-user.php. inside my add-user.php file I have two functions. ->nameTaken functions checks if a username is already in the database, and ->insert inserts names into a database if they are not taken. This file can only be accessed through a post request or else I get 500 server errors and errors that its values are null, see my routes below.

here is the add-user.php file code :

<?php

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

    ]);
};

here is the nameTaken function that is in another 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
            $json = array(
                'success' => true
            );

            echo json_encode($json);

            return false;
        }
    }

This is working properly, but I don't know how to send this information to my html when I'm redirected back to the file with my form, so that it can show a message if a registration was succesful or if it failed because the username is aready taken.

I tried making a json output for this and getting it with a promise, but immediately after the form was submitted I'm redirected to my form page and the ajax call is null. I've only seen questions for how to do this while the username/password is being typed into the registration form on here, but I want to show the message after the registration form is submitted. How would I do this?

my promise ajax request to the php post file :

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/contact.php').then((name) => {
            console.log(name);
        });
    });
}

I can't use this javascript because it executes before the php file is loaded, and then after the php file loads and I'm redirected to the page with my form, everything in the php file is erased, and my promise ajax request has already been executed.

my html :

<form method='POST' action='/users' id='register'>

            Username<input type='text' name='username' required>

            Password<input type='password' name='password' required>

            <button type='submit'>Submit</button>

        </form>

These are the errors I'm getting in my server

[Thu Aug 16 17:38:07 2018] 127.0.0.1:36690 [200]: /
[Thu Aug 16 17:38:07 2018] 127.0.0.1:36694 [200]: /registerFail.js
[Thu Aug 16 17:38:10 2018] PHP Notice:  Undefined index: password in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 5
[Thu Aug 16 17:38:11 2018] PHP Notice:  Undefined variable: app in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7
[Thu Aug 16 17:38:11 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 17:38:11 2018] 127.0.0.1:36734 [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 17:38:11 2018] 127.0.0.1:36738 [302]: /users
[Thu Aug 16 17:38:11 2018] 127.0.0.1:36744 [200]: /
[Thu Aug 16 17:38:11 2018] 127.0.0.1:36750 [200]: /registerFail.js

First I'm on the main '/' page. Immediately when I submit my form, the ajax request runs before the php file is loaded and so everything is undefined, then when my php file loads and checks for the username, everything works fine and the username is either reject or put into my database. Then I'm redirected back to the the '/' directory with my form. I can't show an error message because the ajax executes before the php file is loading and I don't know how to fix this. I want to show the error message when I'm redirected back to the form page after the file has loaded. What would the code look like for me to do this?

<?php

$router->get('', 'controllers/index.php');

$router->get('about', 'controllers/about.php');

$router->get('contact', 'controllers/contact.php');

$router->post('users', 'controllers/add-user.php');

$router->post('login', 'controllers/login.php');

This is my router. controllers/add-user.php does not exist unless I make a post request to it. The other places, I can just type in a url and go to them.

I see this on many websites with a registration, submitting a form and then the page reloads to show if a password/username is taken or incorrect, and I'd appreciate if anyone can show me a link or guide me to anywhere on how this is usually done. I have found this link on youtube https://www.youtube.com/watch?v=DXIIWVR1PLk , but in the video this users route links can be accessed with get requests directly in the url. The page that handles if a username is taken or not for me can only be accessed through a post request, and then it is removed from access without another post request, I can not get it or else I get a 500 server error and other null variable errors. And other plaes I've just seen how to show an error message while the user is typing in a password/username, instead of after a form submission which is what I want.

I'd appreciate any help with this.

  • 写回答

1条回答 默认 最新

  • dongpo7467 2018-08-17 01:23
    关注

    modify your current php and add this else statement.

    if(!$app['database']->nameTaken($_POST['username'])){
        $app['database']->insert('users', [
            'name' => $_POST['username'],
            'password' => $hash
        ]);
    } else {
        $_SESSION["error_msg"] = "That Username belongs to someone else."
    }
    

    Somewhere in your html paste this.

    <?php if (array_key_exists("error_msg", $_SESSION)){
        echo $_SESSION["error_msg"];
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致