function add_comment(ele) {
event.preventDefault();
var username = "<?php echo $current_user; ?>";
var user_id = "<?php echo $current_user_id; ?>";
var post_id = $(ele).data('id');
var comments = $(ele).parent(".comment-section").find(".comment").val();
alert(comments);
if (username == "") {
alert("Please Log in to Star the Post");
window.location = "http://tobbyandscooby.com/log.php";
return;
}
$.ajax({
type: 'POST',
url: 'add_comment.php',
data: {
postid: post_id,
uname: username,
uid: user_id,
comment: comments
},
success: function(response) {
//alert("Successfully Comment is Added! ");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-section">
<textarea id="<?php echo $post_id; ?>" class="comment" value="" data-id="<?php echo $post_id; ?>"></textarea>
<button id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(this);">Comment</button>
<div class="comment-show"></div>
</div>
<?php
include("connect.php");
$username = $_POST['uname'];
$post_id = $_POST['postid'];
$user_id = $_POST['uid'];
$comments = $_POST['comment'];
$sql = "INSERT INTO comments (user_id,username,post_id,comment) VALUES ($user_id,'$username',$post_id,'$comment')";
$result = $db->query($sql);
?>
我正在尝试用ajax制作一个评论系统。我用ajax做过类似的事情,比如favorite,down-vote,upvote。但是现在有了上面的代码,我无法将数据输入到数据库中,而且单击comment按钮页面会刷新,即使我使用了*preventdefault();
我知道我犯了一些错误,但无法调试它。另外,请建议我如何添加到div.comment显示使用ajax的成功输入的评论。
注意:我可以得到警报(评论);默认时工作();函数被删除!我已经添加了xhr对其他工作正常的元素的请求
1条答案
按热度按时间nszi6y051#
问题在于
preventDefault()
.你现在通过了
this
用那个函数调用onClick
.要解决此问题,请通过添加
<button type="submit" ..
然后传球event
使用函数调用:...onClick="add_comment(event);"
```// complete line:
Comment
function add_comment(e) { // whatever you wanna name it, e has to be the same
e.preventDefault(); // as this e