新屏幕上 Json 数据形式的 Codeigniter4 和 Ajax 验证

问题描述 投票:0回答:0

我正在尝试使用 codeigniter4 实现登录表单。我试图使用 ajax 处理验证,但我的代码似乎存在一些问题。我在一个新的空白屏幕上收到验证错误,而不是在有错误的同一屏幕上重定向。 这是我的登录视图

<link type="text/css" rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>">
<script type="text/javascript" src="<?php echo base_url('assets/js/bootstrap.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/jquery/jquery.js'); ?>"></script>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="#">29Kreativ</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="<?= site_url();?>">Home </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="<?= site_url("login");?>">Login</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="<?= site_url("register");?>">Register</a>
      </li>
      
    </ul>
    
  </div>
</nav>


 <div class="card"> 
    <div class="card-body">
<h1>Login Here</h1>
<hr>
<div id="error_message"></div>

<form method="post" action="/login/do_login" id="login-form">
  <div class="form-group mb-3">
    <label for="email">Email address</label> <span id="error_email" class="text-danger ms-3"></span>
    <input type="email" class="form-control " id="email"  name="email" placeholder="Enter email" required>

  </div>
  <div class="form-group mb-3">
    <label for="password">Password</label> <span id="error_password" class="text-danger ms-3"></span>
    <input type="password" class="form-control " id="password" name="password" placeholder="Enter Password" required>
  </div>
   <button type="submit" class="btn btn-primary login-btn">Login</button>
</form>
</div>
</div>

<script>
 $(document).ready(function(){
    $(document).on('click','.login-btn', function(){
        // Validate email and password fields
        if($.trim($('#email').val()).length == 0){
            error_email= 'Please Enter Email Address';
            $('#error_email').text(error_email);
        }
        else{
            error_email= '';
            $('#error_email').text(error_email);
        }

        if($.trim($('#password').val()).length == 0){
            error_password= 'Please Enter Password';
            $('#error_password').text(error_password);
        }
        else{
            error_password= '';
            $('#error_password').text(error_password);
        }

        if(error_email != '' || error_password != '') {
            return false;
        }
        else {
            // Send the Ajax request to validate the login
            $.ajax({
                method: "POST",
                url: "<?php echo site_url('login/do_login'); ?>",
                data: {
                    email: $('#email').val(),
                    password: $('#password').val()
                },
                success: function(response){
                    if (response.status === 'success') {
                        // Login successful, redirect to dashboard
                        window.location.href = '/dashboard';
                    } else {
                        // Login failed, display the validation errors
                        $.each(response.errors, function(key, value){
                            $('#' + key + '_error').text(value);
                        });
                        // Display the error message on the login page
                        $('#error_message').text(response.message);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("Error: " + textStatus);
                }
            });
        }
    });
});

</script>

这是我的登录控制器

<?php

namespace App\Controllers;

use App\Models\UserModel;


class Login extends BaseController
{
    public function __construct()
    {
         
        $this->session  = \Config\Services::session();
        $this->session->start();
    }

    public function index()
    {
        echo view('login');
       
    }

    // public function validate_login()
    // {
    //     helper(['form']);
    //     $validation = \Config\Services::validation();
    
    //     $validation->setRules([
    //         'email' => 'required|valid_email|is_unique[users.email]',
    //         'password' => 'required|min_length[6]'
    //     ]);
    
    //     if (!$validation->withRequest($this->request)->run()) {
    //         // Validation failed, return the errors
    //         return $this->response->setJSON([
    //             'status' => 'error',
    //             'errors' => $validation->getErrors()
    //         ]);
    //     }
    
    //     return $this->response->setJSON([
    //         'status' => 'success',
    //         'message' => 'Login successful!'
    //     ]);
    // }
    
    public function do_login()
    {
        $userModel = new UserModel();
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');
        $result = $userModel->where('email', $email)->first();
    
        if ($result) { 

            helper(['form']);
            $validation = \Config\Services::validation();
        
            $validation->setRules([
                'email' => 'required|valid_email|is_unique[users.email]',
                'password' => 'required|min_length[6]'
            ]);
        
            if (!$validation->withRequest($this->request)->run()) {
                // Validation failed, return the errors
                return $this->response->setJSON([
                    'status' => 'error',
                    'errors' => $validation->getErrors()
                ]);
                // $response = $validation->getErrors();
                // echo $response;
            }
            else{

            if (password_verify($password, $result->password)) {
                $userData = [
                    'id' => $result->id,
                    'isLoggedIn' => true
                ];
                $this->session->set($userData);
                return $this->response->setJSON([
                            'status' => 'success',
                            'message' => 'Login successful!'
                        ]);
                // $response = 'Login Successful!';
                // echo $response;
            } 
        }
    
        return view('login', $data);
    

}}
    
    public function logout()
    {
    $this->session->remove('isLoggedIn');
    //    var_dump('isLoggedIn'); 
     $this->session->destroy();

    // Redirect to login page
     return redirect()->to('/login');
    echo view('dashboard', $data);
 }

    
}





有人可以帮我解决这个问题吗?

php ajax authentication validation codeigniter-4
© www.soinside.com 2019 - 2024. All rights reserved.