如何使用带有动态接受好友按钮的ajax post更新更多的表


How to update more tables using ajax post with dynamic accept friends buttons?

我有一个PHP文件来接受朋友的请求。

PHP

session_start();
include 'db.php';
error_reporting(0);
$username= $_SESSION['username'];
$i=1;
$sql = "SELECT * FROM friends WHERE user2='$username' AND accepted='0' ORDER BY datemade DESC";
$user_query = mysqli_query($db, $sql);
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "<center><p style='padding-left:0px;'>no more friend requests!<p></center>";
}
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$user1 = $row["user1"];
$logged_user= $row["user2"];
$i++;
?>

HTML

<div class="row" id="child" style="background-color: #c2c2c2;">
    <div class="col-md-12">
    <div class="col-md-4" style="margin-top:20px;padding-top: 0px;padding-right:0px;">
`<img src="user/<?php echo $user1; ?>`/profile_pictures/<?php echo $user1; ?>.jpg" width="25px" height="25px"/>
    </div>
    <div class="col-md-8" style="padding-left:0px; margin-left: -10px;">
    <b><?php echo $user1 ?></b><br />
    <div id="accept_div">
    <input id="rcv_user" type="hidden" name="rcv_user" value="<?php echo $logged_user; ?>"/> 
    <input id="snd_usr" type="hidden" name="snd_usr" value="<?php echo $user1; ?>"/> 
    <input id="response" type="hidden" name="response" value="accept"/> 
<span id="accepted" class="" style="display:none">Accepted</span>
<span id="or">or</span> <a id="ignore" href="#"><button class="btn-xs btn-danger">Ignore</button></a>

Javascript/jQuery

$(document).ready(function () {
$('#submit').each(function() {
$(this).click(function() {
 var ths = $(this);
var I = ths.attr("id");
var rcv_user = $(ths).siblings("#rcv_user").val();
var snd_usr = $(ths).siblings("#snd_usr").val();
var response = $(ths).siblings("#response").val();
$.post("respond_friend.php", {rcv_user:rcv_user, snd_usr:snd_usr, response:response},
function(value){
$('#child').css('background-color', 'white');
$("#submit").hide();
$("#ignore").hide();
$("#or").hide();
$("#accepted").show();
}); 
});
});
});

这里的问题是,如果用户收到多个好友请求,那么他只能接受第一个好友请求而其他接受按钮不起作用。刷新页面后,只有下一个接受按钮才能工作。接受一个好友请求需要刷新一次页面。

使用class而不是id。因为id是唯一的。所以你的HTML应该像这个

<span class="accepted">Accepted</span>

而不是

<span id="accepted" class="" style="display:none">Accepted</span>

你的js代码应该像这个

$(function(){
  $('.accepted').on("click", function(){
     var ths = $(this);
     var I = ths.attr("id");
     var rcv_user = $(ths).siblings("#rcv_user").val();
     var snd_usr = $(ths).siblings("#snd_usr").val();
     var response = $(ths).siblings("#response").val();
     $.post("respond_friend.php", {rcv_user:rcv_user, snd_usr:snd_usr, response:response},
     function(value){
        $('#child').css('background-color', 'white');
        $("#submit").hide();
        $("#ignore").hide();
        $("#or").hide();
        $("#accepted").show();
    });  
  })
})