我正在尝试使用Ajax和PHP发送PHP联系表单。在表单中,有一个选择,其中包含多个选项。我从联系表单中获得的结果只在收到的电子邮件中打印了1个值。
这就是我的代码的样子。
HTML
<select multiple="multiple" name="room[]" id="room" required="required" data-error="Please select your preferred bedroom type." size="5">
<option value="" disabled>PREFERRED BEDROOM TYPE</option>
<option value="1 Bedroom">1 Bedroom</option>
<option value="2 Bedroom">2 Bedroom</option>
<option value="3 Bedroom">3 Bedroom</option>
<option value="4 Bedroom">4 Bedroom</option>
</select>
我也是通过ajax .serialize()
发送的PHP
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
$name = $_POST['name'];
$email = $_POST['email'];
// configure
$from = 'Contact Form <abc@gmail.com>';
$reply = "$name<$email>";
$sendTo = 'Contact Form <abc@gmail.com>';
$subject = 'New message from Stirling Residences Contact Form';
$fields = array('name' => 'Name', 'mobile' => 'Mobile', 'email' => 'Email', 'room' => 'Bedroom Type', 'message' => 'Message');
$okMessage = 'Contact form successfully submitted. Thank you, we will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $reply,
'Return-Path: ' . $reply,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
任何帮助都将深表感谢!
答案 0 :(得分:2)
$_POST['room']
的值是一个数组。如果$value
是使用implode()
的数组,则可以使用is_array()
获取所有值。
if (isset($fields[$key])) {
if (is_array($value)) {
$emailText .= "$fields[$key]: ".implode(', ',$value)."\n";
}
else {
$emailText .= "$fields[$key]: $value\n";
}
}
答案 1 :(得分:1)
通过以下代码
更新您的foreach
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
switch($key){
case 'room' :
$emailText .= "$fields[$key]: ". @implode(', ', $value)."\n";
break;
default :
$emailText .= "$fields[$key]: $value\n";
}
}
}