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

Codeigniter Ajax表单验证失败时,如何在模态框显示错误信息?

How to Show Form Validation Errors in Modal via jQuery Ajax in CodeIgniter

Hey there! Since you're new to jQuery Ajax with CodeIgniter, let's break this down step by step. The key here is to adjust your controller to return the right response for Ajax requests, then update your jQuery to handle validation errors and display them in your modal.

Step 1: Update Your Controller's update Method

Your current controller doesn't handle validation failures properly for Ajax. Instead of leaving the if block empty, we'll return a JSON response with either validation errors (or a rendered form with errors) and a status flag. Here are two common approaches:

Option 1: Return Validation Errors as JSON Array

This is great if you want to render errors directly in the existing modal form:

public function update(){
    $this->form_validation->set_rules('lname', 'Family Name', 'required');
    
    if ($this->form_validation->run() == FALSE) {
        // Return validation errors as JSON
        echo json_encode([
            'status' => 'error',
            'errors' => $this->form_validation->error_array()
        ]);
    } else {
        $this->home_model->update();
        // Return success response (no redirect, since Ajax can't follow it)
        echo json_encode([
            'status' => 'success',
            'message' => 'Record updated successfully!'
        ]);
    }
}

Option 2: Return Rendered Form with Errors

If you prefer to reload the entire form (with pre-filled data and errors) into the modal:

public function update(){
    $this->form_validation->set_rules('lname', 'Family Name', 'required');
    $id = $this->input->post('id'); // Get the record ID from form submission
    
    if ($this->form_validation->run() == FALSE) {
        // Fetch the record data again to repopulate the form
        $data['rec'] = $this->home_model->get_single_record($id); // Assume this method exists
        // Render the form view into HTML string
        $form_html = $this->load->view('partials/edit_form', $data, TRUE);
        
        echo json_encode([
            'status' => 'error',
            'form_html' => $form_html
        ]);
    } else {
        $this->home_model->update();
        echo json_encode([
            'status' => 'success',
            'message' => 'Record updated successfully!'
        ]);
    }
}

Step 2: Add jQuery for Form Submission

You already have code to load data into the modal, but you need to handle the form submission via Ajax. Add this to your existing script:

// Handle form submission for update
$(document).on('submit', '#update_form', function(e) {
    e.preventDefault(); // Stop default form submission
    
    $.ajax({
        url: "<?php echo base_url('home/update')?>",
        type: "POST",
        dataType: "JSON",
        data: $(this).serialize(), // Serialize all form data
        success: function(response) {
            if (response.status === 'success') {
                // Success: close modal, show message, refresh page
                $('.updatemodal').modal('hide');
                alert(response.message);
                location.reload(); // Refresh to show updated data
            } else {
                // Validation failed: display errors
                if (response.errors) {
                    // Option 1: Add error messages next to each field
                    // Clear existing errors first
                    $('.text-danger').remove();
                    
                    $.each(response.errors, function(field, errorText) {
                        // Target the input field (e.g., lname_edit for 'lname' field)
                        $('#' + field + '_edit').after('<span class="text-danger">' + errorText + '</span>');
                    });
                } else if (response.form_html) {
                    // Option 2: Replace modal body with the rendered form (with errors)
                    $('.updatemodal .modal-body').html(response.form_html);
                }
                // Ensure the modal stays open
                $('.updatemodal').modal('show');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Error submitting the form. Please try again.');
        }
    });
});

Step 3: Prepare Your Modal Form View

Make sure your form is set up to display errors properly. For example, if using Option 2 (rendered form), your partials/edit_form.php might look like this:

<form id="update_form">
    <input type="hidden" name="id" value="<?php echo $rec['id']; ?>">
    
    <div class="form-group">
        <label for="lname_edit">Family Name</label>
        <input type="text" name="lname" id="lname_edit" 
               value="<?php echo set_value('lname', $rec['lname']); ?>" 
               class="form-control">
        <!-- Show CodeIgniter's validation error here -->
        <?php echo form_error('lname', '<span class="text-danger">', '</span>'); ?>
    </div>
    
    <!-- Add other form fields (fname, mi, bdate, module) similarly -->
    
    <button type="submit" class="btn btn-primary">Update Record</button>
</form>

Key Notes:

  • Avoid redirect() in Ajax responses: Redirects don't work with Ajax requests—instead, return a success status and let JavaScript handle page reloads or navigation.
  • set_value(): Use this to repopulate form fields with user input when validation fails (so users don't lose their data).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:00:17