I am trying to use jQuery for the first time and have a problem returning multiple checkbox values. I thought the following jQuery was correct, however it only returns the first value ‘BLACK’ in the email regardless of what is selected.
Any advice on how to return the selected checkboxes as a list would be much appreciated! Thank you.
*** UPDATED checkbox ID’s to be different from each other ***
PHP & jQUERY:
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function sendSupplierForm() {
var data = {
ordernumber: $("#ordernumber").val(),
servicelist: $("#servicelist").val(),
};
jQuery.ajax({
url: "email.php",
data: data,
dataType:'text',
type: "POST",
success:function(data){
$("#EmailStatus").html(data);
},
error:function (){}
});
}
</script>
<div id="SupplierForm">
<div id="EmailStatus"></div>
<input type="text" name="ordernumber" id="ordernumber" value="456122"><br>
<input class="list" type="checkbox" name="servicelist[]" id="servicelist1" value="BLACK">Black<br>
<input class="list" type="checkbox" name="servicelist[]" id="servicelist2" value="RED">Red<br>
<input class="list" type="checkbox" name="servicelist[]" id="servicelist3" value="YELLOW">Yellow<br>
<div name="submit" class="btnAction" onClick="sendSupplierForm();">Send</div>
</div>
email.php
<?php
$mailto = "info@******.com";
$subject = "Test Form";
$headers = "From: info@******.comnMIME-Version: 1.0nContent-Type: text/html; charset=utf-8n";
$message = "
<html>
<head>
<title>Supplier Form Details</title>
</head>
<body>
<p>Original Order Number: " . $_POST['ordernumber'] . "</p>
<p>Service List: " . $_POST['servicelist'] . "</p>
</body>
</html>
";
// PHP MAILER FUNCTION
$result1 = mail($mailto, $subject, $message, $headers);
// PHP MAILER MESSAGE
if ($result1) {
print "<p class='success'>SUCCESS!!! The details have been sent.</p>";
} else {
print "<p class='Error'>ERROR... Sorry there is a problem sending the details.</p>";
}
?>
3
Answers
A big thank you to @Aro & @ArkDevLarry!
There were two main issues with my code. First, the jQuery was not collecting the values of the checkboxes as mentioned by @Aro, and second, I was too focused on the jQuery and forgot to 'implode' the array of values as mentioned by @ArkDevLarry.
Both suggestions helped me work out the following code which is working perfectly.
I hope this helps someone else who is looking for a similar solution!
Form PHP & JQUERY: (Note: Make sure your path to email.php is correct)
email.php (Note: Make sure you change the email addresses for it to work)
Jquery by default selects the first element so you should take all checkboxes and collect values
}
Also, you have added the same id for all checkboxes, it is incorrect.
The POST values are to be received in the email.php. You cannot treat the servicelist key as a string it is an array of values therefore, you need to loop through Like this.
I hope this solves your problem :).