I need to send an array of products by email with PHP but I’m getting trouble with a “foreach“.
This is my code:
//Form
<form action="" method="post">
<select name="product[]" class="product" >
<option value="product1">product1</option>
<option value="product2">product2</option>
<option value="product3">product3</option>
</select>
<input type="text" name="boxes[]" value="Boxes:" class="boxesInput" size="20">
</form>
This is the jQuery code to grab the data (I’m working on wordpress and couldn’t find a way to do with $_SERVER[‘PHP_SELF’]…
//jQuery
var productVal = jQuery(".product").val();
var boxesVal = jQuery(".boxesInput").val();
jQuery.post("sendemail.php",
{ boxes: boxesVal, product: productVal } );
This is the sendemail.php file
//sendemail.php
$producto = $_POST['product'];
$boxes = $_POST['boxes'];
$body = "Order Details \n" ;
This is the trouble , the foreach:
foreach($producto as $id => $row )
{
$body .= "Product: " . $producto[$id] . "\n";
$body .= "Boxes: " . $boxes[$id] . "\n";
}
$mailTo = 'my@email.com';
$subject = "Quotes Form";
$headers = 'From: <'.$mailTo.'> ' . "\r\n" . 'Reply-To: ' . $mailTo;
mail($mailTo, $subject, $body, $headers);
As Serj points out, you need to serialize the form data in order for php to understand it. Probably better to use
to send your form data. Another problem is that you declare the variable
but the foreach tries to access
$cajas[$id]? if you change your foreach loop toit should work. Note that your form elements are actually suitable to generate arrays as they only take single values.