I have a dropdown list in HTML, with element name staff1, containing names fetched from the database. I need a Send Email button beside the list and once the button is clicked, an email must be sent to the selected option in the list before even submitting the page or form.
Now, I understand that HTML and JavaScript are on the client side, and PHP is on the server side. With my js, I can fetch in real-time the selected value in the dropdown. I came up with below to be able to fetch the selected value via javascript and pass it to PHP for the email function. All of these are in the same file.
<script>
function sendEmail()
{
var val = document.getElementByName("staff1").value;
}
</script>
<?php
$to = "<script>document.writeln(val);</script>";
$subject = "This is a test email";
$txt = "test body";
$headers = "From: aa@123.com";
mail($to,$subject,$txt,$headers);
?>
I would need to call all these in the onclick event of my html a href button. Here is my html:
<a href="#" onclick="sendEmail()" class="button">Send Email</a>
I'm not so sure how all of these three can be integrated together, and I'm still about to learn through AJAX as some other posts suggest. For now, I was hoping a quick solution or workaround would do. I got below but it's not sending anything, even when I temporarily define the $to parameter with a static value. Thanks!
<?php
echo '<a href="#" onclick="sendEmail()" class="button">Send Email</a><br/><br/>';
echo '<script> function sendEmail() { var val = document.getElementByName("staff1").value; } </script>';
$to = "<script>document.writeln(val);</script>";
$subject = "This is a test email";
$txt = "test body";
$headers = "From: aa@123.com";
mail($to,$subject,$txt,$headers);
?>