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

如何在CodeIgniter中通过AJAX点击按钮用一个控制器方法提交两个表单?

Solution for Submitting Two Forms via Single AJAX Button in CodeIgniter

Let's walk through this step-by-step to make your single-button submission work smoothly. I'll cover the frontend setup, AJAX logic, and the CodeIgniter backend handling.

1. Frontend (HTML & JavaScript)

First, give your two forms unique IDs so we can easily grab their data, then add a single button to trigger the AJAX call:

<!-- Form 1 -->
<form id="form1">
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <!-- Add other form 1 fields here -->
</form>

<!-- Form 2 -->
<form id="form2">
    <input type="text" name="address" placeholder="Address">
    <input type="tel" name="phone" placeholder="Phone">
    <!-- Add other form 2 fields here -->
</form>

<!-- Submit Button -->
<button id="submitBoth">Submit Both Forms</button>

Next, add the JavaScript (using jQuery here for simpler AJAX and form handling—just make sure you've included jQuery in your page):

$(document).ready(function() {
    $('#submitBoth').click(function(e) {
        e.preventDefault(); // Stop the button from reloading the page

        // Grab data from both forms and combine them
        var form1Data = $('#form1').serializeArray();
        var form2Data = $('#form2').serializeArray();
        var combinedData = form1Data.concat(form2Data);

        // Add CodeIgniter's CSRF token (critical if CSRF protection is enabled)
        combinedData.push({
            name: '<?= $this->security->get_csrf_token_name() ?>',
            value: '<?= $this->security->get_csrf_hash() ?>'
        });

        // Send the AJAX request
        $.ajax({
            url: '<?= base_url('your_controller/submit_both_forms') ?>', // Replace with your controller/method path
            type: 'POST',
            data: combinedData,
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert('Both forms submitted successfully!');
                    // Optional: Reset the forms after success
                    $('#form1')[0].reset();
                    $('#form2')[0].reset();
                } else {
                    alert('Oops! ' + response.message);
                }
            },
            error: function() {
                alert('Something went wrong with the request. Please try again.');
            }
        });
    });
});

2. CodeIgniter Controller

Create or update your controller (let's call it Your_controller) with a method to handle the combined data:

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

class Your_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Form_model'); // Load your model
        $this->load->library('form_validation'); // For input validation
    }

    public function submit_both_forms() {
        // Set response to JSON format
        $this->output->set_content_type('application/json');

        // Validate form 1 data (adjust rules to match your fields)
        $this->form_validation->set_rules('name', 'Name', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');

        // Validate form 2 data
        $this->form_validation->set_rules('address', 'Address', 'required|trim');
        $this->form_validation->set_rules('phone', 'Phone', 'required|trim');

        if ($this->form_validation->run() === FALSE) {
            // Return validation errors
            $response = [
                'status' => 'error',
                'message' => validation_errors()
            ];
            $this->output->set_output(json_encode($response));
            return;
        }

        // Prepare data for each table
        $form1Data = [
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email')
            // Add other form 1 fields here
        ];

        $form2Data = [
            'address' => $this->input->post('address'),
            'phone' => $this->input->post('phone')
            // Add other form 2 fields here
        ];

        // Insert data via model
        $insertForm1 = $this->Form_model->insert_form1($form1Data);
        $insertForm2 = $this->Form_model->insert_form2($form2Data);

        if ($insertForm1 && $insertForm2) {
            $response = [
                'status' => 'success',
                'message' => 'Data saved to both tables!'
            ];
        } else {
            $response = [
                'status' => 'error',
                'message' => 'Failed to save data to one or both tables.'
            ];
        }

        $this->output->set_output(json_encode($response));
    }
}

3. CodeIgniter Model

Create a model (e.g., Form_model.php) to handle the database inserts:

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

class Form_model extends CI_Model {

    // Insert into first table (replace 'table1' with your actual table name)
    public function insert_form1($data) {
        return $this->db->insert('table1', $data);
    }

    // Insert into second table (replace 'table2' with your actual table name)
    public function insert_form2($data) {
        return $this->db->insert('table2', $data);
    }
}

Quick Tips

  • CSRF Protection: If you have CSRF enabled in CodeIgniter (which is recommended), don't skip adding the CSRF token to your AJAX data—it'll prevent submission errors.
  • Validation: Always validate user input to avoid bad data and security risks. Adjust the validation rules to match your specific field requirements.
  • Error Handling: You can replace the alerts with more polished UI feedback (like displaying errors in a dedicated div) if you want a better user experience.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:27:24