如何在点击「完成合同」按钮时触发运行contract.php生成PDF?
Hey Mike, let's get this sorted out. Since both your database submission and PDF generation features work on their own, we just need to link them together when that button is clicked. Here are two solid approaches, with the first being my top recommendation for reliability:
方案1:后端内部触发(最可靠)
Instead of making the frontend handle two separate requests, we can have your finalizecontract.php call the PDF generation logic right after it successfully saves the data to the database. This way, there's no risk of the PDF trying to read data that hasn't been written yet, and you only need one frontend request.
步骤1:封装PDF生成逻辑
First, extract the core PDF generation code from contract.php into a reusable function in a new file (e.g., generate_contract_pdf.php). This keeps your code clean and avoids conflicts with any output headers in contract.php:
<?php function generateContractPDF($contractId) { // Include TCPDF (adjust the path to match your setup) require_once('tcpdf/tcpdf.php'); // Connect to your database and fetch the contract data using $contractId $dbConnection = new mysqli('localhost', 'your_username', 'your_password', 'your_database'); if ($dbConnection->connect_error) { die("Database connection failed: " . $dbConnection->connect_error); } $stmt = $dbConnection->prepare("SELECT * FROM contracts WHERE id = ?"); $stmt->bind_param("i", $contractId); $stmt->execute(); $contractData = $stmt->get_result()->fetch_assoc(); $stmt->close(); $dbConnection->close(); // Initialize TCPDF and build your contract (use your existing code here) $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $pdf->SetCreator(PDF_CREATOR); $pdf->SetTitle("Signed Contract #" . $contractId); // ... add all your existing PDF content setup, using $contractData to fill fields ... // Save the PDF to your server folder (adjust the path as needed) $savePath = '/path/to/your/server/folder/contract_' . $contractId . '.pdf'; $pdf->Output($savePath, 'F'); // 'F' means save to file, not output to browser return true; } ?>
步骤2:修改finalizecontract.php调用这个函数
After your code successfully inserts/updates the contract data in the database, grab the contract ID (using mysqli_insert_id() if it's a new entry) and call the PDF generation function:
<?php // Handle form submission and save data to database $formData = $_POST; $dbConnection = new mysqli('localhost', 'your_username', 'your_password', 'your_database'); // Example: Insert new contract (adjust to match your table structure) $stmt = $dbConnection->prepare("INSERT INTO contracts (field1, field2) VALUES (?, ?)"); $stmt->bind_param("ss", $formData['field1'], $formData['field2']); $stmt->execute(); if ($stmt->affected_rows > 0) { $contractId = $dbConnection->insert_id; // Get the ID of the new contract $stmt->close(); $dbConnection->close(); // Generate the PDF now that data is saved require_once('generate_contract_pdf.php'); generateContractPDF($contractId); // Send success response to frontend echo json_encode([ 'status' => 'success', 'message' => 'Contract finalized and PDF generated', 'contractId' => $contractId ]); } else { // Handle error case echo json_encode([ 'status' => 'error', 'message' => 'Failed to save contract data' ]); } ?>
方案2:前端顺序AJAX请求
If you prefer not to restructure your backend code, you can have the frontend first send the data to finalizecontract.php, then trigger contract.php only after the first request succeeds. This ensures the database has the latest data before generating the PDF.
Here's an example using jQuery (adjust to match your frontend setup):
$('#finalizeContractBtn').on('click', function(e) { e.preventDefault(); const formData = $('#yourContractForm').serialize(); // First: Submit data to finalizecontract.php $.ajax({ url: 'finalizecontract.php', method: 'POST', data: formData, dataType: 'json', success: function(response) { if (response.status === 'success') { // Second: Trigger PDF generation with the contract ID $.ajax({ url: 'contract.php', method: 'POST', data: { contractId: response.contractId }, success: function() { alert('Contract completed and PDF saved!'); }, error: function() { alert('Contract data saved, but PDF generation failed.'); } }); } else { alert('Failed to save contract data: ' + response.message); } }, error: function() { alert('Could not connect to server to save contract.'); } }); });
Note: Make sure contract.php is set to save the PDF to the server (using Output('F') instead of Output('I')) and can accept the contractId parameter to fetch the correct data.
内容的提问来源于stack exchange,提问作者mike437

