I am trying to send emails to certain people depending on the button that is chosen, the table in the interface consists of two fields, the name of the person and the button that, when clicked, will send the email.
I build this table through a loop of an array previously taken from the database that contains the ids of the people.
echo '<legend>Enviar correos</legend>';
echo '<table>';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
echo '<td>'.ucwords(getNameEmp($row['employee'])).'</td>';
echo '<td><button type="button" class="btn btn-default" name="send" value="'.$row['employee'].'" id="send"><span class="glyphicon glyphicon-send" aria-hidden="true"></span></button></td>';
echo '</tr>';
}
echo '</table>';
And my ajax request is this:
$("#send").click('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "sendMails.php",
type: "POST",
data: {
id: $(this).val()
},
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
}));
My question is, what is the best way to know which button was selected to know which person the email should be sent to?
It is wrong to use the same id as it should only be unique. In your case, each row has the same id, "send", and you cannot identify which button is the one that sends.
I suggest you delete the id="send" part .
On the other hand, the javascript must locate each button independently. I recommend that you change the javascript to:
I have changed the selector so that it looks for all those that have the value send as the name attribute (in your case all the buttons). On the other hand, the value will be the $this (the button you clicked) and .value().
Try like this:
Then in ajax:
I added the email class to the button as a selector for jquery and ajax and in ajax change the selector and add the id socket like this:
$(this).attr('data-id')