如何从CodeIgniter模型返回新增3条记录ID至控制器并用于AJAX
Alright, let's walk through how to get those 3 newly inserted record IDs back to your AJAX callback. Here's what you need to adjust in your CodeIgniter code:
1. Update the Model Method
First, fix your inserPaymentAllocation method (note the typo in the name—should be insertPaymentAllocation) to return the last inserted ID instead of just a boolean. CodeIgniter provides $this->db->insert_id() which grabs the auto-increment ID of the most recent insert.
public function insertPaymentAllocation($data){ // Remove the print_r and exit lines—they're blocking execution if($this->db->insert('payment_rec_allocn', $data)){ return $this->db->insert_id(); // Return the new record's ID } else { return false; // Return false if insertion fails } }
2. Modify the Controller to Collect IDs
In your controller, you'll need to collect each inserted ID during the loop instead of overwriting a single variable. We'll also track if all inserts succeed, and include the IDs in the JSON response.
public function createPaymentAllocation(){ $bilty_ids = $this->input->post('due_ids'); $biltyCount = count($bilty_ids); $agent = $this->input->post('agent'); $due_to = $this->input->post('due_to'); $inserted_ids = []; // Array to store all successful IDs $all_success = true; // Flag to check if all inserts worked for($i = 0; $i < $biltyCount; $i++){ $data = array( 'agent_id' => $agent, 'pay_dueto' => $due_to, 'mr_no' => $bilty_ids[$i], ); $new_id = $this->PayRecAllModel->insertPaymentAllocation($data); if($new_id){ $inserted_ids[] = $new_id; // Add the ID to our array $this->PayRecAllModel->changeStatus($bilty_ids[$i]); // Only update status if insert succeeded } else { $all_success = false; // Mark as failed if any insert fails break; // Optional: Stop processing further records if one fails } } if($all_success && !empty($inserted_ids)){ $data['PaymentRecAllocation'] = array( 'form_status' => 'true', 'form_message' => 'Payment Recovery has been successfully Allocated', 'inserted_ids' => $inserted_ids // Include the IDs in the response ); } else { $data['PaymentRecAllocation'] = array( 'form_status' => 'false', 'form_message' => 'Something went wrong.', 'inserted_ids' => $inserted_ids // Optional: Return partial IDs if some succeeded ); } echo json_encode($data); }
3. Use the IDs in AJAX Success Callback
Finally, in your frontend AJAX code, you can access the inserted_ids array from the response and use it for your printing logic:
// Example AJAX call $.ajax({ url: '/your-controller-path/createPaymentAllocation', // Replace with your actual URL type: 'POST', data: $('your-form-selector').serialize(), // Or your form data object dataType: 'json', success: function(response){ const paymentResponse = response.PaymentRecAllocation; if(paymentResponse.form_status === 'true'){ const ids = paymentResponse.inserted_ids; console.log('Successfully inserted records with IDs:', ids); // Your printing logic here—loop through the IDs as needed ids.forEach(id => { console.log('Processing record ID:', id); // Add code to trigger print for each ID }); } else { alert(paymentResponse.form_message); } }, error: function(){ alert('Request failed. Please try again.'); } });
Key Notes:
- Make sure to remove the
print_r($this->input->post()); exit();line from your model—it was stopping execution before the insert could complete. - If you want to allow partial inserts (continue even if one fails), remove the
break;line in the controller loop. - The
inserted_idsarray will contain all IDs that were successfully inserted, even if some fail (if you skip thebreak).
内容的提问来源于stack exchange,提问作者farhantechno

