How do I transfer data to the View?

Viewed 30

I work on php MVC pattern. I have a problem with passing the error 'incorrect login or password' after entering in the form. The form is sent, the page is reloaded, but the error is not displayed. We need your help!

js

const loginForm = document.getElementById('loginForm');
loginForm.addEventListener("submit", loginFormSend);
async function loginFormSend(e) {
    e.preventDefault();
    const data = new FormData(loginForm);

    const res = await fetch('/login', {
        method: 'POST',
        body: data,
    });
    
    res.json()
        .then(i => i?.res && location.reload())       
        .then(i => i?.res || location.reload());
}

controller_login.php

$this->pageData['title'] = "Sign In";
        if (!empty($_POST)) {
            $action = $_POST['action'];

            if ($action == 'login') {
                if (!$this->model->entry()) {
                    $this->pageData['loginError'] = "Incorrect login or password";
                }
                echo json_encode([
                    'res' => $this->model->entry(),  
                ]);
            }
        } else {
            $this->view->non_template("login_view.php", $this->pageData);
        }

model_controller.php

public function entry(): bool
    {
        $login = $_POST['login'];
        $password = md5($_POST['password']);

        $sql = "SELECT * FROM user WHERE login = :login AND password = :password";

        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':login', $login, PDO::PARAM_STR);
        $stmt->bindValue(':password', $password, PDO::PARAM_STR);
        $stmt->execute();

        $res = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!empty($res)) {
            setcookie('user', $res['login'], strtotime('+30 days'));
            return true;
        } else {
            return false;
        }
    }

the line , where the error should be displayed above the form

<input type="hidden" name="action" value="login">
                    <?php if (!empty($pageData['loginError'])) : ?>
                        <p class="color-red"><?php echo $pageData['loginError']; ?></p>
                    <?php endif; ?>
0 Answers
Related