0

I have tried to get the ID of the dynamically generated button in the following way. I tried to get the particular button ID and use it for beforeSend:function(id). But it isn't successful.

<?php
session_start();
require_once "../auth/dbconnection.php";

$output ='';

$sql= "SELECT * FROM appointment AS a INNER JOIN prescription as p ON a.apt_id=p.apt_id INNER JOIN users as u ON u.user_id=a.user_id AND a.p_id='".$_POST["id"]."'";

$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){

$output .='
<table class="table table-striped custom-table mb-0">
   <thead>
      <tr>
         <th>Appointment ID</th>
         <th>Prescription ID</th>
         <th>Doctor Name</th>
         <th>Specilization</th>
         <th>Appointment Date </th>                             
         <th>Action</th> 
         <th>Status</th> 
      </tr>
    </thead>';                                 
     while($row=mysqli_fetch_array($result)){
     $output .='
      <tr>
          <td><a href="#">'.$row["apt_id"].'</a></td>
          <td id="pres"><a href="#">'.$row["pres_id"].'</a></td>
          <td>'.$row["username"].'</td>
          <td><span class="custom-badge status-blue">'.$row["specilization"].'</span></td>
          <td>'.$row["apt_date"].'</td>
          <td>                             
          <button id="check'.$row["pres_id"].'" class="btn btn-danger custom-badge status-grey" value="Submit"  data-id='.$row['pres_id'].' onclick="alert(this.id)">   Submit  </button> </td>    
          <td> <span id="status" name="status"></span> </td>                                 
      </tr>';
}                                                 
}else{
    $output .=  '
<tr>
<td colspan="5" align="center"> No more prescriptions available :-( </td>
</tr>';

}
echo $output;   
?>

Here is my jquery

$(document).on("click","button",function(){
    
   var id = $(this).attr("data-id");

    $.ajax({
     url:"delete_record.php",
     method:"POST",
     data:{id:id},
     beforeSend:function(id)
{
    $("#check"+id).val("Checking......");
  
},   
     success:function(data){
      $('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
      location.reload();
     }
    });
    setInterval(function(){
     $('#alert_message').html('');
    }, 5000); 
  });
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

1

I would give your button element a custom class, eg delete-btn

class="btn btn-danger custom-badge status-grey delete-btn"

Then modify your click event to listen for that specific button:

$(document).on("click",".delete-btn",function(){ .. }

To get the data attribute value of the button that was clicked use .data():

var btnDataId = $(this).data('id');

To get the id attribute value of the button that was clicked use .attr():

var btnAttrId = $(this).attr('id');

You can just use $(this) with .text() to change the display value:

$(this).text('Checking..');

Also worth noting is that you can improve the efficiency of your code by storing any reused jquery objects in a variable so that jquery doesn't ahve to instantiate the same object over and over. In this case your code is using $(this) more than once so you should: var self = $(this); and then use the self variable in all instances that you are currently using $(this).

The following is a complete example of all points talked about above:

$(document).on("click",".delete-btn",function(){
   var self = $(this); 
   var id = self.data("id");

    $.ajax({
     url:"delete_record.php",
     method:"POST",
     data:{id:id},
     beforeSend:function(id)
     {
       self.text("Checking......");
  
     },   
     success:function(data){
      $('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
      location.reload();
     }
    });
    setInterval(function(){
     $('#alert_message').html('');
    }, 5000); 
  });
Drew
  • 4,215
  • 3
  • 26
  • 40
  • The data attribute value is needed for the ajax – charlietfl Sep 20 '20 at 16:19
  • Ah yes I see that now. However, adding the custom class to your button element's and listening for the click of just those buttons will fix your issue. Your current binding will fire the function for any button located anywhere on the page when it is clicked – Drew Sep 20 '20 at 16:23
  • I am not the OP. Was just pointing out OP doesn't need to get the element id. Also they are recognizing they already have a reference to that button and don't need to search dom again for it – charlietfl Sep 20 '20 at 16:25
  • Please note! Your code introduces an SQL injection vulnerability because the post parameter is concatenated to the SQL string without any further counter measures. See https://stackoverflow.com/questions/2087182/is-sql-injection-possible-with-post/2087192#2087192 Edit: not speaking about the code provided in this answer, but code of OP – martinspielmann Sep 20 '20 at 18:04
1

I see you've already found an answer, but I just wanted to throw in my two cents for future/others reference.

First, I hope you're doing some iota of sanitation and not just dropping the clients $_POST right into your query. Here are the first three google results on that.

Second, your code is kind of tough to read. I would recommend using double quotes " for all strings in php, and escaping them \" when needed in a string. Just simplifies and standardizes everything. This may have been where your original problem came from as well.

'<button id="check'.$row["pres_id"].'" class="btn btn-danger custom-badge status-grey" value="Submit"  data-id='.$row['pres_id'].' onclick="alert(this.id)">   Submit  </button>'

Assuming $row["pres_id"] = 123, it would render as

<button id="check123" class="btn btn-danger custom-badge status-grey" value="Submit" data-id=123 onclick="alert(this.id)"> Submit </button>

Notice that it's missing double quotes for the data-id value. Using double quotes, you can just drop an array value into a string by surrounding it with {}. So your code would simplify to

"<button id=\"check{$row["pres_id"]}\" class=\"btn btn-danger custom-badge status-grey\" value=\"Submit\"  data-id=\"{$row["pres_id"]}\" onclick=\"alert(this.id)\">   Submit  </button>"

I guess my IDE does it slightly more justice with the color scheme, but either way, I think it's slightly more readable and helps prevent missing escaping charters or leaving them out entirely. Also, with double quotes, you can drop a variable into a string and it will just parse it correctly, no string concatenation required!

Say $id = $row["pres_id"], now you can just

"<button id=\"check$id\" class=\"btn btn-danger custom-badge status-grey\" value=\"Submit\"  data-id=\"$id\" onclick=\"alert(this.id)\">   Submit  </button>"

Here's a slightly better read on the nuances of php strings.

PoorlyWrittenCode
  • 1,003
  • 1
  • 7
  • 10