PHP AJAX使用while循环提交表单

时间:2016-10-23 15:38:28

标签: javascript php jquery html ajax

我正在制作实时评论功能。这里的问题是,当我评论时,评论成功但数据插入的次数与while循环中的表格一样多。我想我应该从表状态为每个表单分配一个单独的状态ID(sts_id)并在我的ajax代码中进行更改,这样它只提交一次数据,而不是提交在while循环中创建表单的次数。例如,由于表单处于while循环中并且有6个状态帖,因此当我评论状态时,评论将被插入6次。还有一个问题就是,评论功能目前仅在while循环内的第一个表单上工作。在其他表格中,表格提交不起作用,即不提交评论。我认为添加单独的ID也可以解决这个问题。请帮忙。

HTML部分

<script>
       function ajaxFunction(){
  var ajaxRequest; 
  try{
      ajaxRequest = new XMLHttpRequest();
  }catch (e){
      try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {
        try{
           ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }catch (e){
           // Something went wrong
           alert("Your browser broke!");
           return false;
        }
      }
  }
  $('.commentarea').keydown(function(event) {
    var id = $(this).attr('id');
    var status_id = id.replace("postcomment_", "");
    if($.trim($("#postcomment_"+status_id).val())) {
      if(event.keyCode == 13) {
        event.preventDefault();
        $("form#form_id_"+status_id).on('submit', function (e) {
          e.preventDefault();
          var comment = $('#postcomment_'+status_id).val();
          var statsid = status_id;
          var myData = {"comment": comment, "statsid": statsid};
          $.ajax({
            url: "post-comment.php",
            type: "POST",
            data: myData,
            success: function (data, status, xhr) {
              $(".showbox").html(data); // output result
              $('#postcomment').val('');
            }
          });
        });
      }
    }
  });
}
</script>

    <div class="stats-cont">
<?php 
$get_sts = "SELECT * FROM status LEFT JOIN members ON status.sts_mem = members.mem_id ORDER BY sts_time DESC";

$get_stq = $pdo->prepare($get_sts);
$get_stq->execute();

while($get_stf = $get_stq->fetch()){ extract($get_stf); 

$get_cmts = "SELECT * FROM comments WHERE cmt_status = :status ORDER BY cmt_id ASC";
$get_cmtq = $pdo->prepare($get_cmts);
$get_cmtq->bindValue(':status', $sts_id);
$get_cmtq->execute();
$total_cmts = $get_cmtq->rowCount();
?>
<div class="status-note-block status-container">
  <div class="member-name-container">
    <div class="mem-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="40" width="40">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="40" width="40">
      <?php } ?>
    </div>
    <div class="member-name"><?php echo $mem_name; ?><br>
      <small>
      <?php if((date("Y-m-d", strtotime($sts_time))) == $curr_date){ echo "Today"; }else if((date("Y-m-d", strtotime($sts_time))) == $yest){ echo "Yesterday"; }else{ echo date("jS F", strtotime($sts_time)); } ?>
      <?php echo date("h:i a", strtotime($sts_time)); ?> </small> </div>
  </div>
  <div class="status-block"><?php echo $sts_status; ?></div>
</div>
<div class="comment-block">
  <div class="comment-reaction-holder"></div>
  <?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); ?>
  <div class="comment-flex-holder">
    <div class="comment-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="30" width="30">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="30" width="30">
      <?php } ?>
    </div>
    <div class="showbox"><font color="#5B5899" style="font-size: 12px"><b><?php echo $mem_name; ?></b></font> <?php echo $cmt_comment; ?><br />
      <font style="font-size:12px">Like &middot; Reply &middot; Just now</font></div>
  </div>
  <br />
  <?php } ?>
    <div id="showbox"></div>
  <div class="commet-field-holder">
    <div class="comment-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="30" width="30">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="30" width="30">
      <?php } ?>
    </div>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="form_id_<?php echo $sts_id?>">
      <input type="hidden" name="status_id" value="<?php echo $sts_id; ?>" id="statsid_<?php echo $sts_id?>" />
      <textarea name="comment" placeholder="Give a comment..." class="comment-field commentarea" id="postcomment_<?php echo $sts_id?>" onclick='ajaxFunction()'></textarea>
    </form>
  </div>
</div>
<?php } ?>

post-comment.php部分:

    <?php
//error_reporting(0);
include('config/db.php');
$time = date('Y-m-d H:i:s');

$content   = (!empty($_POST['comment']))?$_POST['comment']:null;
$status_id = (!empty($_POST['statsid']))?$_POST['statsid']:null;

$insert = "INSERT INTO `comments`(`cmt_comment`,`cmt_status`, `cmt_time`)VALUES(:comment, :status, :time)";
$inserq = $pdo->prepare($insert);
$inserq->bindValue(':comment', $content);
$inserq->bindValue(':status', $status_id);
$inserq->bindValue(':time', $time);
$inserq->execute();
$lastid = $pdo->lastInsertId();

$sel = "SELECT * FROM comments 
        LEFT JOIN status ON comments.cmt_status = status.sts_id 
        LEFT JOIN members ON members.mem_id = status.sts_mem
        WHERE comments.cmt_id = :lastid";
$seq = $pdo->prepare($sel);
$seq->bindValue(':lastid', $lastid);
$seq->execute();
$sef = $seq->fetch();
?>

<div class="comment-flex-holder">
  <div class="comment-img-thumb">
    <?php if($sef['mem_image'] == null){ ?>
    <img src="images/user.png" height="30" width="30">
    <?php }else{ ?>
    <img src="users/<?php echo $sef['mem_image']; ?>" height="30" width="30">
    <?php } ?>
  </div>
  <div class="showbox"><font color="#5B5899" style="font-size: 12px"><b><?php echo $sef['mem_name']; ?></b></font> <?php echo $sef['cmt_comment']; ?><br />
    <font style="font-size:12px">Like &middot; Reply &middot; Just now</font></div>
</div>
<br />

2 个答案:

答案 0 :(得分:2)

因为,While循环有n个形式。所以,每个表格和输入值将具有不同的ID。在您的问题中,每个输入都声明了相同的ID。因此,不允许使用具有相同名称的多个ID。 ID不能相同。

首先,您需要更改每个输入ID。更简单的方法是,为每个ID附加状态ID。它会自动更改。

如果您想使用此答案,则需要按原样复制我的答案。而不是在您的代码中修改。因为,你可能会留下几行,后来的结果会变成“不工作”。所以,试试这个代码。如果有任何问题,请随意询问。

更新代码

<script>
function ajaxFunction(){
  var ajaxRequest; 
  try{
      ajaxRequest = new XMLHttpRequest();
  }catch (e){
      try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {
        try{
           ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }catch (e){
           // Something went wrong
           alert("Your browser broke!");
           return false;
        }
      }
  }
  $('.commentarea').keydown(function(event) {
    var id = $(this).attr('id');
    var status_id = id.replace("postcomment_", "");
    if ($.trim($("#postcomment_"+status_id).val())) {
      if (event.keyCode == 13) {
        event.preventDefault();
        $("form#form_id_"+status_id).on('submit', function (e) {
          e.preventDefault();
          var comment = $('#postcomment_'+status_id).val();
          var statsid = status_id;
          var myData = {"comment": comment, "statsid": statsid};
          $.ajax({
            url: "post-comment.php",
            type: "POST",
            data: myData,
            success: function (data, status, xhr) {
              $(".showbox").html(data); // output result
              $('#postcomment').val();
            }
          });
        });
      }
    }
  });
}
</script>

<div class="stats-cont">
<?php 
$get_sts = "SELECT * FROM status LEFT JOIN members ON status.sts_mem = members.mem_id ORDER BY sts_time DESC";

$get_stq = $pdo->prepare($get_sts);
$get_stq->execute();

while($get_stf = $get_stq->fetch()){ extract($get_stf); 

$get_cmts = "SELECT * FROM comments WHERE cmt_status = :status ORDER BY cmt_id ASC";
$get_cmtq = $pdo->prepare($get_cmts);
$get_cmtq->bindValue(':status', $sts_id);
$get_cmtq->execute();
$total_cmts = $get_cmtq->rowCount();
$fetch_cmts = $get_cmtq->fetch();
?>
<div class="status-note-block status-container">
  <div class="member-name-container">
    <div class="mem-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="40" width="40">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="40" width="40">
      <?php } ?>
    </div>
    <div class="member-name"><?php echo $mem_name; ?><br>
      <small>
      <?php if((date("Y-m-d", strtotime($sts_time))) == $curr_date){ echo "Today"; }else if((date("Y-m-d", strtotime($sts_time))) == $yest){ echo "Yesterday"; }else{ echo date("jS F", strtotime($sts_time)); } ?>
      <?php echo date("h:i a", strtotime($sts_time)); ?> </small> </div>
  </div>
  <div class="status-block"><?php echo $sts_status; ?></div>
</div>
<div class="comment-block">
  <div class="comment-reaction-holder"></div>
  <div class="commet-field-holder">
    <div class="comment-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="30" width="30">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="30" width="30">
      <?php } ?>
    </div>
    <div class="showbox"></div>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="form_id_<?=$sts_id?>">
      <input type="hidden" name="status_id" value="<?php echo $sts_id; ?>" id="statsid_<?=$sts_id?>" />
      <textarea name="comment" placeholder="Give a comment..." class="comment-field commentarea" id="postcomment_<?=$sts_id?>" onclick='ajaxFunction()'></textarea>
    </form>
  </div>
</div>
<?php } ?>

修改1

<script>
    function ajaxFunction(){
      var ajaxRequest; 
      try{
          ajaxRequest = new XMLHttpRequest();
      }catch (e){
          try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
          }catch (e) {
            try{
               ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
               // Something went wrong
               alert("Your browser broke!");
               return false;
            }
          }
      }
      $('.commentarea').keydown(function(event) {
              var id = $(this).attr('id');
              var status_id = id.replace("postcomment_", "");
              if ($.trim($("#postcomment_"+status_id).val())) {
                if (event.keyCode == 13) {
                        event.preventDefault();
                        postcomment(status_id);
                }
              }
            });
            function postcomment(status_id){
                var comment = $('#postcomment_'+status_id).val();
                    var statsid = status_id;
                    var myData = {"comment": comment, "statsid": statsid};
                    $.ajax({
                        url: "post-comment.php",
                        type: "POST",
                        data: myData,
                        success: function (data, status, xhr) {
                            $(".showbox").html(data); // output result
                            $('#postcomment').val();
                        }
                    });
            }
    }
    </script>

答案 1 :(得分:0)

要在评论框中保持唯一性,您应该使用计数器。这将创建动态名称和ID。同样你需要在ajax调用$(this).attr('data-counter')

中获取

您可以查看以下代码并根据需要进行设置。

<script>
    function ajaxFunction(){
        var ajaxRequest; 
        try{
            ajaxRequest = new XMLHttpRequest();
        }catch (e){
            try{
              ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }catch (e) {
              try{
                 ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
              }catch (e){
                 // Something went wrong
                 alert("Your browser broke!");
                 return false;
              }
            }
        } 
    $('.postcomment').keydown(function(event) {
        if($.trim($(".postcomment").val())) {
            if(event.keyCode == 13) {
                event.preventDefault();
                $("form.cmtform").submit();
            }
        }   
    });
    $("form.cmtform").on('submit', function(e) {
        e.preventDefault();
        var counter_val = $(this).attr('data-counter');
        var comment = $('#postcomment_' + counter_val).val(); 
        var statsid = $('#statsid_' + counter_val).val(); 
        var myData={"comment":comment, "statsid":statsid};
        $.ajax({
            url : "post-comment.php",
            type: "POST",
            data : myData,
            success: function(data,status,xhr){
                $(".showbox").html(data); // output result
                $('#postcomment_' + counter_val).val();
            }
        }); 
    }); 
    }
</script>

<div class="stats-cont">
<?php 
    $get_sts = "SELECT * FROM status LEFT JOIN members ON status.sts_mem = members.mem_id ORDER BY sts_time DESC";

$get_stq = $pdo->prepare($get_sts);
$get_stq->execute();
    $counter = 1;
    while($get_stf = $get_stq->fetch()){ extract($get_stf); 

    $get_cmts = "SELECT * FROM comments WHERE cmt_status = :status ORDER BY cmt_id ASC";
    $get_cmtq = $pdo->prepare($get_cmts);
    $get_cmtq->bindValue(':status', $sts_id);
    $get_cmtq->execute();
    $total_cmts = $get_cmtq->rowCount();
    $fetch_cmts = $get_cmtq->fetch();
?>
<div class="status-note-block status-container">
  <div class="member-name-container">
    <div class="mem-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="40" width="40">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="40" width="40">
      <?php } ?>
    </div>
    <div class="member-name"><?php echo $mem_name; ?><br>
      <small>
      <?php if((date("Y-m-d", strtotime($sts_time))) == $curr_date){ echo "Today"; }else if((date("Y-m-d", strtotime($sts_time))) == $yest){ echo "Yesterday"; }else{ echo date("jS F", strtotime($sts_time)); } ?>
      <?php echo date("h:i a", strtotime($sts_time)); ?> </small> </div>
  </div>
  <div class="status-block"><?php echo $sts_status; ?></div>
</div>
<div class="comment-block">
  <div class="comment-reaction-holder"></div>
  <div class="commet-field-holder">
    <div class="comment-img-thumb">
      <?php if($mem_image == null){ ?>
      <img src="images/user.png" height="30" width="30">
      <?php }else{ ?>
      <img src="users/<?php echo $mem_image; ?>" height="30" width="30">
      <?php } ?>
    </div>
    <div class="showbox"></div>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" data-counter="<?php echo $counter;?>">
       <input type="hidden" name="status_id_<?php echo $counter;?>" value="<?php echo $sts_id; ?>" id="statsid_<?php echo $counter;?>" />
      <textarea name="comment_<?php echo $counter;?>" placeholder="Give a comment..." class="postcomment comment-field commentarea" id="postcomment_<?php echo $counter;?>" onclick='ajaxFunction()'></textarea>
     </form>
  </div>
</div>
    <?php 
    $counter++;
} 
?>

干杯!!