0
我正在製作一個表單來發布數據,並結合Ajax。以下是與之相關的所有代碼。問題是,填寫表單並提交時,首次點擊它執行XHR請求,並獲得成功回調,將按鈕更改爲完成!第二次提交AJAX請求帖子
但結果不會出現在數據庫中。當再次點擊提交按鈕時,它會完成另一個XHR請求。任何想法可能導致這種情況?謝謝!
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
} catch (Exception $e) {
echo $e->getMessage();
}
} ?>
// Backend for the authenication and validation (where the form posts to)
<?php
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if(isset($post_title) && isset($post_content) && isset($post_id)){
if(empty($post_title)){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if(!$login->updatePost($post_id, $post_title, $post_content)){
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>
// JS for the Ajax request itself
$("form").submit(function(evt){
evt .preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax(url, {
data: formData,
type: "POST",
success: function(response){
if(response == "allrighty"){
$(".update-submit").prop("value", "Done!")
}
else if (response == "charliewegotaproblem") {
$(".update-submit").prop("value", "Something went wrong...")
}
}
}); // Ajax OBJECT END;
});// Submit END
什麼是預期行爲?在第一次點擊時使用ajax更新數據庫,或者在第二次點擊時提交'form'?什麼是做!!$ login-> updatePost($ post_id,$ post_title,$ post_content)'? –
它正在更新數據庫中的一篇文章,稍後檢索(CMS)。它應該更新與更改後的數據庫。這發生了,但第二次點擊(它確實更新了第一次點擊按鈕的文本,這應該只會發生,如果方法運行成功,並輸出「allrighty」)事實並非如此。 – Uberfume
!$ login-> updatePost($ post_id,$ post_title,$ post_content)是更新數據庫的方法(請參閱代碼帖子的頂部)(編輯:更新爲正確的方法) – Uberfume