[英]Save data to MySQL and update page with that data without refresh
我正在嘗試將評論表單中的數據保存到MySQL數據庫中,然后使用該注釋更新頁面,而無需用戶刷新。 類似於Facebook評論的工作方式。
我到處搜索了這個問題的答案,但我找不到符合我需求的答案。
這是將表單數據提交到php腳本的AJAX:
var ajaxSubmit = function(formEl) {
// fetch where we want to submit the form to
var url = $(formEl).attr('action');
// fetch the data for the form
var data = $(formEl).serializeArray();
// setup the ajax request
$.ajax({
url: url,
data: data,
dataType: 'json',
success: function(data) {
if(rsp.success) {
alert("Comment Successfully Added!");
}
});
return false;
}
我知道目前不會使用此腳本更新頁面,因為我正在調用警報。 但是,當我提交數據時,我將被帶到/ajax/comment.process.php
頁面,該頁面是調用insertComment()
函數並將注釋插入數據庫的頁面。 我現在在success()
函數中有alert()
函數,我甚至沒有得到它。
我想要的是,當提交評論時,用戶不會離開當前頁面,只是更新他們剛提交的內容。
這是/ajax/comment.process.php'
的代碼
session_start();
include_once('../classes/comment.class.php');
include_once('../classes/db.class.php');
$user_id = $_SESSION['user_id'];
$db = new DBConnection;
$comments = new Comment($db);
$blog_id = intval($_POST['blogID']);
$addCom = $comments->addComment($user_id);
if($addCom === FALSE) {
$resp = "<span class='error'>Error adding comment</span>";
} else {
$resp = $comments->getComments($blog_id);
}
return $resp;
此腳本調用insertComment()
函數將注釋保存到數據庫,然后如果返回true,則調用getComments()
函數,該函數檢索該特定帖子的注釋並將其存儲在數組中。
這些評論被成功保存到數據庫中,但我重定向到ajax/comment.process.php
頁是空白。 如何使用他們發布的評論更新當前頁面而無需刷新頁面? 我認為返回$resp
變量會執行它然后我可以只做一個foreach()
循環來顯示它們,但顯然不是這種情況。
編輯:我已經在下面的答案中提出了一切建議,我還沒有解決這個問題。 表單是STILL提交給/ajax/comment.process.php
即使我有三個應該阻止提交表單的東西: preventDefault();
, return false;
並return ajaxSubmit(this);
在ajax中你可以刪除dataType: 'json',
並刪除if(rsp.success) {
並發出一個簡單的警報
$.ajax({
url: url,
data: data,
success: function(data) {
alert("Comment Successfully Added!");
alert(data);
}
});
在php而不是你正在使用的返回中,使用echo
echo $resp;
至少你會看到是否有錯誤
之后,您可以開始使用json代碼
在PHP中
echo json_encode($resp);//as soon as $resp is an array
並且在ajax中你可以像這個alert(data.keyofthearray)
一樣alert(data.keyofthearray)
要防止表單提交(正在發生的事情),請使用onsubmit="return ajaxSubmit(this);"
你的ajax代碼中也有語法錯誤。 你永遠不會關閉if
塊
var data = $(formEl).serialize();
$.ajax({
url: url,
data: data,
dataType: 'json',
success: function(data) {
if(data.success) {
alert("Comment Successfully Added!");
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.