skip to Main Content

I have a button in a row of data in datatables, if the button is clicked, the modal will open and user can update some data, the data is taken using ajax and sent to another php file.
my table
modal open when the button is clicked

The problem is, when i clicked the button, the row i get is always 1 (the first row), so the data in the first row will be the one updated instead of the row where the button is clicked. Here is the code for the button.

            <td>
          
            <?php 
              if ($row['status'] == 0){
            ?>
            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#modalEdit"  name="buttonModal" id="buttonModal" data-row="<?php echo $row['id'];?>">
              <i class="far fa-edit"></i>
            </button>
          
            <?php
              }else{
            ?>
            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#modalEdit"  name="buttonModal" id="buttonModal" data-row="<?php echo $row['id'];?>"disabled>
              <i class="far fa-edit"></i>
            </button>
            
            <?php
              }
            ?>
          </td>

The modal:

<div class="modal" id="modalEdit">
      <div class="modal-dialog">
          <div class="modal-content">
              <!-- Modal Header -->
              <div class="modal-header text-light" style="background-color: #FF9B6A">
                  <h4 class="modal-title">Edit Status Pembayaran Peserta</h4>
                  <button type="button" class="close" data-dismiss="modal">&times;</button>
              </div>
              <!-- Modal body -->
              <div class="modal-body">
              <tr>
                  <div class="form-check">
                    <form method="POST">
                      <input class="form-check-input" type="radio" name="status" id="approved" value="1">
                      <label class="form-check-label" for="approved"> Approved </label>
                      <br>
                      <input class="form-check-input" type="radio" name="status" id="rejected" value="2">
                      <label class="form-check-label" for="rejected"> Rejected </label>
                    </form>
                  </div>
              </tr>
              <tr>
                  <td colspan="2">Catatan untuk peserta: </td>
              </tr>
              <tr>
                  <td colspan="2">
                      <textarea class="form-control" id="catatan" placeholder="Catatan"></textarea>
                  </td>
                  <p style="font-size: 14px">Di isi jika ada</p>
              </tr>
              </div>
              <div class="modal-footer">
              <p style="color: red">Setelah Anda mengedit, maka sistem secara otomatis akan mengirimkan E-mail mengenai status pembayaran kepada peserta yang bersangkutan.</p>
              <button type="submit" class="btn btn-primary" id="submit">Save</button>
              <button type="button" class="btn btn-primary" data-dismiss="modal" id="close">Close</button>
              </div>
          </div>
      </div>
  </div>

The script:

<script>
$(document).ready(function() {
    $('#table').DataTable();
    $("#submit").click(function(){
        // if($('#status').val() != "" && $('#data-row').val() != ""){
        if($('#status').val() != "" ){
            var status = $("input[type='radio']:checked").val();

            var element = document.getElementById('buttonModal');
            var row = element.getAttribute('data-row');
            alert(row);

            let fd = new FormData();
            fd.append("status",status);
            fd.append("row",row);
            $.ajax({
                url: "sisiAdmin_action.php",
                method: "POST",
                data: fd,
                processData: false,
                contentType: false,
                success: function (res) {
                    // alert(res);
                    if(res == 'Berhasil update status'){
                        Swal.fire({
                        position: 'top-middle',
                        icon: 'success',
                        title: 'Berhasil update status',
                        showConfirmButton: false,
                        timer: 2000
                        })
                        $('#status').val("");
                        $('#data-row').val("");
                    }
                    else{
                        Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Gagal update status'
                        })
                    }
                },
                error: function () {
                    alert("Gagal");
                } 
            });
        }
        else{
            Swal.fire('Data belum lengkap!')
        }
    });
    $(document).ajaxStop(function(){
        window.location.reload();
    });
  });
</script>

UPDATE: I managed to open the modal through button onclick with this, but still can’t get the row number…

 $(document).on('click','#buttonModal',function(){
  $("#modalEdit").modal('show');
});

UPDATE 2: I got the row by doing this now i have to find out how to get the int value from {"row": int}

var id;
$(document).on('click','#buttonModal',function(){
  $("#modalEdit").modal('show');
  id = $(this).data();
  var str = JSON.stringify(id);
  alert(JSON.stringify(id));
});

UPDATE 3: Okay, i did it. Here’s how i get the row id

var id;
var row;
$(document).on('click','#buttonModal',function(){
  $("#modalEdit").modal('show');
  id = $(this).data();
  var str = JSON.stringify(id);
  const obj = JSON.parse(str);
  row = obj.row;
  // alert(row);
});

2

Answers


  1. Using the id attribute in multiple places makes your code invalid.

    It looks like you were looking for data after click, I can suggest you use the event parameter in the callback and use that to figure out which button is clicked. For more detail look at https://api.jquery.com/submit/

    Login or Signup to reply.
  2. first of all, you must prevent setting non-unique id to your elements, it’s important to have a distinct id attribute name per each element of your DOM, according to html living standard :

    The class, id, and slot attributes may be specified on all HTML elements. ……. When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element’s tree and must contain at least one character. The value must not contain any ASCII whitespace.

    after that, when u trigger an event on $("#submit") element then you cannot get previous triggered target to fetch row id from it, so by selecting var element = document.getElementById('buttonModal'); u just get the first one.

    the solution is to run modal programmatically by JavaScript :

    $("#myModal").modal('show');
    

    when click event on row triggered :

    $(document).ready(function(){
        $("#buttonModal").click(function(){
            $("#modalEdit").modal('show');
        });
    });
    

    now put an hidden input element in edit modal form :

     <input type="hidden" name="row_id" id="row_container">
    

    and before showing modal set it as well :

    $(document).ready(function(){
        $("#buttonModal").click(function(event){
            $("#row_container").value($(this).data('row'));
            $("#modalEdit").modal('show');
        });
    });
    

    then send the form .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search