這是我的代碼,我通過comment
和帖子ID(隱藏輸入標籤)到另一個php文件comments.php
應該插入到數據庫並顯示結果,但它沒有發生。在使用AJAX和PHP的帖子評論系統
這是我的形式 - 在回聲報碼一部分......我有每個職位相關的自動遞增pid
所以對於每一個評論,在comment
和pid
被存儲在數據庫中:
<form method=\"POST\" onSubmit=\"comment(); return false;\">
<input id=\"comment\" type=\"text\" placeholder=\"Add Comment...\" name=\"comment\">
<input type=\"hidden\" name=\"pid\" value=\"".$row['pid']."\">
<div class=\"z\"><input type=\"submit\" name=\"submit\" ></div>
</form>
JavaScript - 使用onsubmit
針對每個帖子的評論表單調用函數comment()
。
function comment() {
jQuery.ajax({
url: "comments.php",
data: $('form').serialize(),
type: "POST",
success:function(data){
$("#".$row['pid']).html(data);
},
error:function(){
}
});
}
這是comments.php
代碼:
<?php
session_start();
include 'db.php';
$j =$_POST['comment'];
$k = $_POST['pid'];
$l =$_SESSION['uname'];
$sql = "INSERT INTO comments (pid,name,comment) values ('$k','$l','$j')";
$r = $conn->prepare($sql);
$r->execute();
if($r) {
echo '<div class="comment">
<a class="avatar">
<img style="height:30px;"src="zmf.jpg">
</a>
<div class="content">
<a class="author">'.$l.'</a>
<div class="metadata">
<span class="date">Today at 5:42PM</span>
</div>
<div class="text">';
echo $j.'</div>
<div class="actions">
</div>
</div>
</div>
';
}
?>
什麼comments.php
應該返回將在div
顯示在index.php
具有已被指定在index.php中每個崗位的id = #postid
:
<div id=\"".$row['pid']."\">
</div>
index.php
對於每個po都有這樣的div
st所以發表評論的帖子,評論將顯示在每個帖子下方的div
。任何幫助,將不勝感激。
我運行兩個while循環來顯示每個帖子的所有previuos評論像這樣。 第一個循環顯示帖子和一個嵌套的while循環,每個帖子顯示每個帖子的評論。每個帖子在while循環中的評論表單以及具有id = postid的div以顯示ajax結果。
$q = $conn->prepare("SELECT * FROM posts ORDER BY pid DESC");
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)) {
#my post in div
#comment form
<form method=\"POST\" onsubmit=\"comment()\">
<input id=\"comment\" type=\"text\" placeholder=\"Add Comment...\" name=\"comment\">
<input type=\"hidden\" name=\"pid\" value=\"".$row['pid']."\">
<div class=\"z\"><input type=\"submit\" name=\"submit\" ></div>
</form>
#div where recent comment is shown using ajax
<div id=\"".$row['pid']."\">
</div>
#nested while loop for comments
$zmf = "SELECT * FROM comments WHERE pid = '" . $row['pid'] . "' ORDER BY comid DESC";
$zed = $conn->prepare($zmf);
$zed->execute();
$run = $zed->fetch();
while($run = $zed->fetch())
{
my div code and all..for comments
}
}
每一個崗位都有一個id PID .. 但其NT工作..plz幫助
您可以顯示完整的腳本,你'在你的JavaScript()激活'有何評論? – Rasclatt
多數民衆贊成在我的文件中唯一的js部分..還有什麼? –
哦,對不起,我看到你做了什麼,你有內聯。好吧,不要理會! – Rasclatt