Shubham Jha Shubham Jha - 1 month ago 9
Ajax Question

jQuery Ajax function working for only first result in while loop

My jQuery Ajax function is only working for the 1st result from the while loop. When I enter a data and press enter the data is insert to the database but this only works with the 1st form which is the 1st result from the while loop. With other forms generated from the while loop its not working. I have
even assigned a unique ID but still its not working.

jQuery Ajax function:

$(document).on('keydown', '.replyarea', function(event) {
var comtr = $(".replyarea").val();
if(comtr!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var rid = $(this).attr('id');
var commentId = rid.replace("replycomment_", "");
createReply(commentId);
event.preventDefault();
}
}
});

function createReply(commentId){
var creply = $('#replycomment_'+commentId).val();
$.ajax({
url: "post-replies.php",type: "POST",
data: {creply : creply, cmtid : commentId},
success: function (data) {
$("#showreply_"+commentId).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#replycomment_'+commentId).val('');
}
})
}


PHP:

<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); ?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">

<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />

<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>

</form>

<?php } ?>

Answer

I changed $(document).on('keydown', '.replyarea', function(event) { to $('.replyarea').keydown(function (event) { and it worked for me. Modified few lines of code. It may help you.

$('.replyarea').keydown(function (event) {
  if (event.keyCode == 13) {
    var id = $(this).attr('id'); 
    var commentId = id.replace("replycomment_", "");
    var reply = $("#replycomment_"+commentId).val();
    if(reply != ""){
      event.preventDefault();
      createReply(commentId);
    }
  }
});

function createReply(commentId){
  var creply = $('#replycomment_'+commentId).val();
  $.ajax({
      url: "post-replies.php",type: "POST",
      data: {creply : creply, cmtid : commentId},
      success: function (data) {
        $("#showreply_"+commentId).append(data);
      },
      error: function () {
        alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
      },
      complete: function(xhr) {
        $('#replycomment_'+commentId).val('');
      }
  })
}
Comments