我很新來使用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提交表單? –
提交後您的輸入內容爲空? –