Home » Php » php – How to post an Ajax onClick through a looping input form (Dinamically) from MySql query result

php – How to post an Ajax onClick through a looping input form (Dinamically) from MySql query result

Posted by: admin February 25, 2020 Leave a comment

Questions:

I would like to be suggested on how to solve an Ajax post through a looping input form (Dynamically) from MySql query result.

<?php
// Query Result
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
  <div class="media-body text-muted text-small">
    <input class="d-none" value="'.$row->cY.'" name="post_X" id="post_X">
    <input class="d-none" value="'.$row->cZ.'" name="post_Y" id="post_Y">
    <div class="input-group">                             
      <input style="background:#fafafa" type="text" name="post_Z" id="post_Z" placeholder="Join conversation here..." class="form-control">
      <div class="input-group-append">
        <button type="button" onclick="addPost()" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
      </div>
    </div>
  </div>
</div>';
}
?>

Ajax script

<script>
function addPost() {
    if(!$("#post_Z").val()) {
        // An Alert!
    } else {
        var post_X = $("#post_X").val();
        var post_Y = $("#post_Y").val();
        var post_Z = $("#post_Z").val();
        $.post("reply.php", {
            uid: post_X,
            cid: post_Y,
            txt: post_Z
        }, function (data, status) {
            // An Alert!
        });
    };
}
</script>

Thanks alot

How to&Answers:

give an id for each iteration, and add the id in the addPost event so that the post only retrieves data according to the id that is defined

change the code to be like this

<?php
// Query Result

$uniq = 1;
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
  <div class="media-body text-muted text-small">
    <input class="d-none" value="'.$row->cY.'" name="post_X_'.$uniq.'" id="post_X_'.$uniq.'">
    <input class="d-none" value="'.$row->cZ.'" name="post_Y_'.$uniq.'" id="post_Y_'.$uniq.'">
    <div class="input-group">                             
      <input style="background:#fafafa" type="text" name="post_Z_'.$uniq.'" id="post_Z_'.$uniq.'" placeholder="Join conversation here..." class="form-control">
      <div class="input-group-append">
        <button type="button" onclick="addPost('.$uniq.')" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
      </div>
    </div>
  </div>
</div>';
$uniq++;
}
?>

and the ajax

<script>
function addPost(id) {
    if(!$("#post_Z_"+id).val()) {
        // An Alert!
    } else {
        var post_X = $("#post_X_"+id).val();
        var post_Y = $("#post_Y_"+id).val();
        var post_Z = $("#post_Z_"+id).val();
        $.post("reply.php", {
            uid: post_X,
            cid: post_Y,
            txt: post_Z
        }, function (data, status) {
            // An Alert!
        });
    };
}
</script>

may these help