在ajax-api请求中多次插入数据库

时间:2018-07-07 06:26:11

标签: php jquery mysql ajax

我正在建立一个社交网站。我的comment-like/dislike函数有问题。每当单击like/dislike按钮时,类似计数都会正常更新,但是我会在comment_likes/dislikes表中多次插入,这会导致在通知表中多次插入(对于所有帖子ID)。我认为该错误是由对API的jquery ajax调用引起的。我要去哪里了?以下内容是我的个人资料页面javascript和comment_likes api(类似于comment_dislikes)。我什至配置了posts和comments api来返回合并的JSON post和comments,但是没有用。我需要在其特定帖子下方加载每个评论...帖子赞/不喜欢功能可以正常工作。

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "../api/profile-posts-old?username=<?php echo $_GET['username'];?>",
        processData: false,
        contentType: "application/json",
        data: '',
        success: function(r) {
            var posts = JSON.parse(r);
            $.each(posts, function(index) {
            	//load content from db
                $('.timelineposts').html(
                    $('.timelineposts').html() + '<div class="box box-widget"><div class="box-header with-border"><div class="user-block"><img class="img-circle" src="'+posts[index].ProfileImg+'" alt="User Image"><span class="username"><a href="#">'+posts[index].PostedBy+'</a></span><span class="description">Shared publicly - '+posts[index].PostDate+'</span></div><div class="box-tools"><button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-ellipsis-h"></i></button></div></div><div class="box-body"><p>'+posts[index].PostBody+'</p><ul class="list-inline"><li><a data-id="'+posts[index].PostId+'" href="javascript:void(0)" class="link-black text-sm"><i class="fa fa-thumbs-o-up margin-r-5"></i>'+posts[index].Likes+'</a></li><li><a data-did="'+posts[index].PostId+'" href="javascript:void(0)" class="fixmargin link-black text-sm"><i class="fa fa-thumbs-o-down margin-r-5"></i>'+posts[index].Dislikes+'</a></li><li class="pull-right"><a id=\"nof_com'+posts[index].PostId+'\" href="javascript:void(0)" class="link-black text-sm"><i class="fa fa-comments-o margin-r-5"></i></a></li></ul></div><div id=\"post_com'+posts[index].PostId+'\"></div><div class="box-footer"><form method="post"><img class="img-responsive img-circle img-sm" src="'+posts[index].LogUserImg+'" alt="Alt Text"><div class="input-group img-push"><input type="text" name="postbody" placeholder="Your thoughts? ..." class="form-control '+posts[index].PostId+'"><span class="input-group-btn"><button type="button" data-comid=\"'+posts[index].PostId+'\" class="btn btn-primary btn-flat">Send</button></span></div></form></div></div>'
                );
                //allow users to comment on a post
                $('[data-comid]').click(function() {
                    var buttonid = $(this).attr('data-comid');
                    $.ajax({
                        type: "POST",
                        url: "../api/comments?postid=" + $(this).attr('data-comid'),
                        processData: false,
                        contentType: "application/json",
                        data: '{ "body": "'+ $("."+buttonid).val() +'" }',
                        success: function(r) {
                            location.reload();
                        },
                        error: function(r) {
                            console.log(r);
                        }
                    });
                });
                //get post id to send to comment api
                var buttonid = posts[index].PostId;
                //load comment for every post
                $.ajax({
                    type: "GET",
                    url: "../api/comments?postid=" + buttonid,
                    processData: false,
                    contentType: "application/json",
                    data: '',
                    success: function(r) {
                        var comments = JSON.parse(r);
                        //
                        $.each(comments, function(index) {
                        	//load comments 
                            $('#post_com'+buttonid).html(
                                $('#post_com'+buttonid).html() + '<div class="box-footer box-comments"><div class="box-comment"><img class="img-circle img-sm" src="'+comments[index].ProfileImg+'" alt="User Image"><div class="comment-text"><span class="username">'+comments[index].CommentedBy+'<span class="text-muted pull-right">'+comments[index].CommentDate+'</span></span>'+comments[index].Comment+'<ul class="list-inline"><li><a data-comlid="'+comments[index].ComId+'" href="javascript:void(0)" class="link-black text-sm"><i class="fa fa-thumbs-o-up margin-r-5"></i>'+comments[index].Likes+'</a></li><li><a data-comdid="'+comments[index].ComId+'" href="javascript:void(0)" class="fixmargin link-black text-sm"><i class="fa fa-thumbs-o-down margin-r-5"></i>'+comments[index].Dislikes+'</a></li></ul></div></div></div>'
                            );
                        });
                        //allow users to like comment
                        $('[data-comlid]').click(function() {
                            var buttonid_two = $(this).attr('data-comlid');
                            $.ajax({
                                type: "POST",
                                url: "../api/comment-likes?comid="+$(this).attr('data-comlid')+"&postid=" + buttonid,
                                processData: false,
                                contentType: "application/json",
                                data: '',
                                success: function(r) {
                                    var res = JSON.parse(r);
                                    $("[data-comlid='"+buttonid_two+"']").html('<i class="fa fa-thumbs-o-up"></i> '+res.Likes);
                                    console.log(r);
                                },
                                error: function(r) {
                                    console.log(r);
                                }
                            });
                        });
                        //allow users to dislike comment
                        $('[data-comdid]').click(function() {
                            var buttonid_three = $(this).attr('data-comdid');
                            $.ajax({
                                type: "POST",
                                url: "../api/comment-dislikes?comid="+$(this).attr('data-comdid')+"&postid=" + buttonid,
                                processData: false,
                                contentType: "application/json",
                                data: '',
                                success: function(r) {
                                    var res = JSON.parse(r);
                                    $("[data-comdid='"+buttonid_three+"']").html('<i class="fa fa-thumbs-o-down"></i> '+res.Dislikes);
                                    console.log(r);
                                },
                                error: function(r) {
                                    console.log(r);
                                }
                            });
                        });
                    },
                    error: function(r) {
                        console.log(r);
                    }
                });
                //allow users to like post
                $('[data-id]').click(function() {
                    var buttonid = $(this).attr('data-id');
                    $.ajax({
                        type: "POST",
                        url: "../api/post-likes?id=" + $(this).attr('data-id'),
                        processData: false,
                        contentType: "application/json",
                        data: '',
                        success: function(r) {
                            var res = JSON.parse(r);
                            $("[data-id='"+buttonid+"']").html('<i class="fa fa-thumbs-o-up"></i> '+res.Likes);
                            console.log(r);
                        },
                        error: function(r) {
                            console.log(r);
                        }
                    });
                });
                //allow users to dislike post
                $('[data-did]').click(function() {
                    var buttonid = $(this).attr('data-did');
                    $.ajax({
                        type: "POST",
                        url: "../api/post-dislikes?id=" + $(this).attr('data-did'),
                        processData: false,
                        contentType: "application/json",
                        data: '',
                        success: function(r) {
                            var res = JSON.parse(r);
                            $("[data-did='"+buttonid+"']").html('<i class="fa fa-thumbs-o-down"></i> '+res.Dislikes);
                            console.log(r);
                        },
                        error: function(r) {
                            console.log(r);
                        }
                    });
                });
            });
        },
        error: function(r) {
            console.log(r);
        }
    });
});

$postId = $_GET['postid'];
$comId = $_GET['comid'];
$token = $_COOKIE['SNID'];
$likerId = $db->query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($token)))[0]['user_id'];
if (!$db->query('SELECT user_id FROM comment_likes WHERE post_id=:postid AND user_id=:userid AND comment_id=:comid', array(':postid'=>$postId, ':userid'=>$likerId, ':comid'=>$comId))) {
	if (!$db->query('SELECT user_id FROM comment_dislikes WHERE post_id=:postid AND user_id=:userid AND comment_id=:comid', array(':postid'=>$postId, ':userid'=>$likerId, ':comid'=>$comId))) {
			$db->query('UPDATE comments SET likes=likes+1 WHERE id=:comid AND post_id=:postid', array(':comid'=>$comId, ':postid'=>$postId));
			$db->query('INSERT INTO comment_likes VALUES(\'\', :postid, :userid, :comid)', array(':postid'=>$postId, ':userid'=>$likerId, ':comid'=>$comId));
				$temp = $db->query('SELECT comments.user_id AS receiver, comment_likes.user_id AS sender FROM comments, comment_likes WHERE comments.id = comment_likes.comment_id AND comments.id=:comid', array(':comid'=>$comId));
				$r = $temp[0]["receiver"];
				$s = $temp[0]["sender"];
				$db->query('INSERT INTO notifications VALUES (\'\', :type, :receiver, :sender, :post_id, :comid, 0, NOW(), :extra)', array(':type'=>2, ':receiver'=>$r, ':sender'=>$s, ':post_id'=>$postId, ':comid'=>$comId, ':extra'=>""));
	}else {
		die('already liked or disliked comment');
	}
}else {
		$temp = $db->query('SELECT comments.user_id AS receiver, comment_likes.user_id AS sender FROM comments, comment_likes WHERE comments.id = comment_likes.comment_id AND comments.id=:comid', array(':comid'=>$comId));
		$r = $temp[0]["receiver"];
		$s = $temp[0]["sender"];
		$db->query('DELETE FROM notifications WHERE type=2 AND receiver=:receiver AND sender=:sender AND post_id=:postid AND comment_id=:comid', array(':receiver'=>$r, ':sender'=>$s, ':postid'=>$postId, ':comid'=>$comId));
	$db->query('UPDATE comments SET likes=likes-1 WHERE id=:comid AND post_id=:postid', array(':comid'=>$comId, ':postid'=>$postId));
	$db->query('DELETE FROM comment_likes WHERE post_id=:postid AND user_id=:userid AND comment_id=:comid', array(':postid'=>$postId, ':userid'=>$likerId, ':comid'=>$comId));
}
echo "{";
echo '"Likes":';
echo $db->query('SELECT likes FROM comments WHERE id=:comid', array(':comid'=>$comId))[0]['likes'];
echo "}";

1 个答案:

答案 0 :(得分:0)

我将所有AJAX请求都包装在函数中,从而解决了问题