我决定第一次使用 ajax 来提交我的数据,但我遇到了问题。表单似乎已重置,但没有数据发送到数据库,我可能在这里遗漏了一些明显的东西:
jQuery(目前包含在我的文件头中)
<script>
// jQuery to submit form data via AJAX to add a recovery pack
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}}
</script>
PHP/HTML 表单
<form id="rpack_add_form" class='small_form' name='rpack_form' method='post' onsubmit="return submitForm();">
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for 2nd form at a later date</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for 3rd form at a later date</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add Recovery Pack' name='add_rpack'>
</form>
<div class="form_result"> </div>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
addrpack.php 的 PHP(当我从上面删除 ajax 部分并正常提交时,此代码完全有效)
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if a number has been entered
if (empty ($number))
{
echo "You need to enter a number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}