我很新来使用AJAX进行表单提交,并且一直在关注它的使用方面的很多教程,但是我似乎无法在当前场景中使用它。提交表单时使用AJAX
我有一个内部形式的模式链接到一个PHP脚本和一些JQuery AJAX。
当我提交表单的页面显示为白色时,我确信这是因为我的PHP脚本中的条件逻辑。
所以,我有$stmt->rowCount()
和条件逻辑它没有返回任何内容,因为脚本在这一点上什么也不做。
我可以将此逻辑链接到AJAX成功或失败,还是必须从我的脚本返回布尔值?
我知道这可能被认为是一个愚蠢的问题,但一些清晰度会有很大的用处。
形式
<form id="userForm" method="post" action="test/process_data.php">
<div class="form-group">
<label for="email">First name:</label>
<input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>
</div>
<div class="form-group">
<label for="email">Surname:</label>
<input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="[email protected]">
</div>
<div class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" name="company" id="company" placeholder="Company name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<a href="" class="btn btn-default">Just take me to the partner</a>
</form>
AJAX脚本
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
$("#forename").val('');
$("#surname").val('');
$("#email").val('');
$("#company").val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
}
</script>
PHP脚本来处理数据
if (empty($_POST["forename"]) ||
empty($_POST["surname"]) ||
empty($_POST["email"]) ||
empty($_POST["company"]))
{
}
else{
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email_address = $_POST['email'];
$company_name = $_POST['company'];
$id = rand();
$date_time = date('Y-m-d');
try
{
// Construct the SQL to add a book to the database
$sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
// Prepare the SQL and bind parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam(':forename', $forename);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':email_address', $email_address);
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':date_time', $date_time);
$stmt->execute();
// If the statement affected the database
if ($stmt->rowCount() > 0)
{
}
else{
}
} catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
使用表单或AJAX,但不要同时使用两者。 –
@ScottMarcus什么?为什么有人不能使用AJAX提交表单? –
提交后您的输入内容为空? –