You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter中Ajax实现用户注册校验及表单提交技术咨询

Hey there! Let's walk through how to implement your Ajax-based user verification and form submission in CodeIgniter step by step. I'll split this into frontend and backend sections to make it easy to follow, since you're new to Ajax.

1. Update Your Frontend Form & Add Ajax Logic

First, let's tweak your existing form to work with Ajax—we'll prevent default page reloads and add security measures required by CodeIgniter. Here's the modified form:

<form class="form-group" id="userVerificationForm" action="<?php echo site_url('home/verify_usr'); ?>" method="post">
    <!-- Add CodeIgniter CSRF token (critical for security) -->
    <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
    <table style="width: 100%;">
        <tr>
            <td>
                <input class="form-control" type="text" name="reg_id" id="reg_id" placeholder="Enter the User ID here.." aria-label="Search" style="width: 100%">
            </td>
            <td>
                <!-- Switch to a regular button to trigger Ajax (instead of auto-submitting) -->
                <button type="button" id="submitBtn" class="btn btn-danger">Submit</button>
            </td>
        </tr>
        <tr>
            <td style="text-align: center;color: red">
                <span id="fails"><!-- Verification messages will show here --></span>
            </td>
        </tr>
    </table>
</form>

<!-- Optional container to display registered user data -->
<div id="userDataContainer" style="display: none; margin-top: 20px;">
    <h4>Registered User Details</h4>
    <p><strong>User ID:</strong> <span id="displayUserId"></span></p>
    <p><strong>Name:</strong> <span id="displayUserName"></span></p>
    <!-- Add more fields based on your user table structure -->
</div>

Quick Explanation:

  • We added a CSRF token to comply with CodeIgniter's default security rules.
  • Changed the submit button to a regular button to avoid automatic page reloads.
  • Added a hidden container to display user data if the ID is registered.

Next, add this jQuery Ajax script (ensure jQuery is loaded in your page—you can download it locally and include it instead of using external links):

$(document).ready(function() {
    $('#submitBtn').click(function() {
        // Clear previous messages/data
        $('#fails').text('');
        $('#userDataContainer').hide();

        // Grab input values and CSRF token
        var regId = $('#reg_id').val().trim();
        var csrfTokenName = $('[name="<?php echo $this->security->get_csrf_token_name(); ?>"]').attr('name');
        var csrfTokenValue = $('[name="<?php echo $this->security->get_csrf_token_name(); ?>"]').val();

        // Basic input validation
        if (regId === '') {
            $('#fails').text('Please enter a valid User ID.');
            return;
        }

        // Send Ajax request to CodeIgniter backend
        $.ajax({
            url: $('#userVerificationForm').attr('action'),
            type: 'POST',
            data: {
                reg_id: regId,
                [csrfTokenName]: csrfTokenValue
            },
            dataType: 'json',
            success: function(response) {
                // Update CSRF token for future requests (good practice)
                $('[name="<?php echo $this->security->get_csrf_token_name(); ?>"]').val(response.csrf_hash);

                if (response.success) {
                    // User is registered: show their data
                    $('#displayUserId').text(response.user.id);
                    $('#displayUserName').text(response.user.name);
                    $('#userDataContainer').show();

                    // Uncomment below if you need to submit the form for further processing
                    // $('#userVerificationForm').submit();
                } else {
                    // User not registered: show error message
                    $('#fails').text(response.message);
                }
            },
            error: function() {
                $('#fails').text('Oops! Something went wrong. Please try again.');
            }
        });
    });
});
2. CodeIgniter Backend Controller (Home.php)

Now set up the verify_usr method in your Home controller to handle the Ajax request, check the database, and return a JSON response:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Load database library (skip if already autoloaded in config/autoload.php)
        $this->load->database();
        // Load security library for CSRF handling
        $this->load->library('security');
    }

    public function verify_usr() {
        // Block non-Ajax requests for security
        if (!$this->input->is_ajax_request()) {
            exit('Direct script access is not allowed.');
        }

        $reg_id = $this->input->post('reg_id');

        // Query your database to check if the user exists
        // Replace 'users' with your actual table name, 'id' with your user ID column
        $this->db->where('id', $reg_id);
        $query = $this->db->get('users');

        $response = [];
        // Generate new CSRF token for subsequent requests
        $response['csrf_hash'] = $this->security->get_csrf_hash();

        if ($query->num_rows() > 0) {
            // User exists: return success and their data
            $response['success'] = true;
            $response['user'] = $query->row_array(); // Get user data as an associative array
        } else {
            // User doesn't exist: return error message
            $response['success'] = false;
            $response['message'] = 'User not registered.';
        }

        // Send JSON response to frontend
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
}

Quick Explanation:

  • We first validate that the request is an Ajax request to block direct access.
  • Queries the database for the provided User ID.
  • Returns a JSON response with either user data (if registered) or an error message (if not).
  • Updates the CSRF token to maintain security for future interactions.
3. Key Notes for Beginners
  • Double-check your database configuration in application/config/database.php to ensure CodeIgniter can connect to your database.
  • Replace the table name (users) and column name (id) with your actual database structure.
  • If you don't have jQuery, download it from the official site and include it in your page's <head> section.

内容的提问来源于stack exchange,提问作者sreeraj t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:53:32