简体   繁体   中英

Send email array (foreach)

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

$.post("sendmail.php", $("form").serialize());

to send your form data. Another problem is that you declare the variable

$boxes = $_POST['boxes'];

but the foreach tries to access $cajas[$id] ? if you change your foreach loop to

foreach($producto as $id => $row )
{
 $body .= "Producto: " .  $producto[$id]  . "\n";
 $body .= "Cajas: " .  $boxes[$id]  . "\n"; 
} 

it should work. Note that your form elements are actually suitable to generate arrays as they only take single values.

jQuery.val will create a JavaScript array, which is not compatible with a PHP array. You would need to serialize in JavaScript and unserialize in PHP:

This is one such function: http://code.activestate.com/recipes/414334-pass-javascript-arrays-to-php/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM