WP + AJAX success message - php

I have a multilingual website where I should show a success message after successful submission. I use ACF filed and wp_send_json_success () to report a successful send, but I get an error in the console. The letter was sent successfully. How can I do it correctly so that I can send a success message?
PHP:
add_action('wp_ajax_nopriv_send_email', 'send_email');
add_action('wp_ajax_send_email', 'send_email');
function send_email() {
$checkbox = $_POST['myCheckboxes'];
if (isset($checkbox)) {
echo $checkbox;
}
$checkbox_hy = $_POST['myCheckboxesHy'];
if (isset($checkbox_hy)) {
echo $checkbox_hy;
}
$checkbox_modal_2 = $_POST['modalCheckboks2'];
if (isset($checkbox_modal_2)) {
echo $checkbox_modal_2;
}
$checkbox_subs = $_POST['subsCheckbox'];
if (isset($checkbox_subs)) {
echo $checkbox_subs;
}
$checkbox_sp = $_POST['supportCheckbox'];
if (isset($checkbox_sp)) {
echo $checkbox_sp;
}
$headers = 'Content-Type: text/html; charset="utf-8"';
$url = $_POST['url'];
$name = $_POST['name'];
$fullname = $_POST['fullname'];
$spFullname = $_POST['spFullname'];
$hy_name = $_POST['hy_name'];
$from = 'contact#test.com';
$to = 'contact#test.com';
$email = $_POST['email'];
$hy_email = $_POST['hy_email'];
$spEmail = $_POST['spEmail'];
$modalEmail = $_POST['modalEmail'];
$subsEmail = $_POST['subsEmail'];
$msg = $_POST['msg'];
$hy_msg = $_POST['hy_msg'];
$modalMsg = $_POST['modalMsg'];
$spMsg = $_POST['spMsg'];
$company = $_POST['company'];
$spCompany = $_POST['spCompany'];
if ($hy_name) {
$subject = '‘Any questions?’ form: ' . $_POST['hy_email'];
} elseif ($name) {
$subject = 'Footer form: ' . $_POST['email'];
} elseif ($fullname) {
$subject = 'Header form: ' . $_POST['modalEmail'];
} elseif ($subsEmail) {
$subject = 'New blog subscription: ' . $_POST['subsEmail'];
} elseif ($spEmail) {
$subject = 'Support form: ' . $_POST['spEmail'];
}
$message .= (!empty($name)) ? '<p><strong>User Name</strong> : ' . $name .' </p>' : '';
$message .= (!empty($email)) ? '<p><strong>User Email</strong> : '. $email .'</p>' : '';
$message .= (!empty($msg)) ? '<p><strong>User Message</strong> : '.$msg .'</p>' : '';
$message .= (!empty($checkbox)) ? '<p><strong>Checkboxs</strong> : '.$checkbox .'</p>' : '';
$message .= (!empty($hy_name)) ? '<p><strong>User Name</strong> : '.$hy_name .'</p>' : '';
$message .= (!empty($hy_email)) ? '<p><strong>User Email</strong> : '.$hy_email .'</p>' : '';
$message .= (!empty($hy_msg)) ? '<p><strong>User Message</strong> : '.$hy_msg .'</p>' : '';
$message .= (!empty($checkbox_hy)) ? '<p><strong>Checkbox</strong> : '.$checkbox_hy .'</p>' : '';
$message .= (!empty($fullname)) ? '<p><strong>Full Name</strong> : ' . $fullname .' </p>' : '';
$message .= (!empty($modalEmail)) ? '<p><strong>User Email</strong> : ' . $modalEmail .' </p>' : '';
$message .= (!empty($company)) ? '<p><strong>Company</strong> : ' . $company .' </p>' : '';
$message .= (!empty($modalMsg)) ? '<p><strong>User Message</strong> : ' . $modalMsg .' </p>' : '';
$message .= (!empty($checkbox_modal_2)) ? '<p><strong>Checkbox</strong> : '.$checkbox_modal_2 .'</p>' : '';
$message .= (!empty($subsEmail)) ? '<p><strong>User Email</strong> : '. $subsEmail .'</p>' : '';
$message .= (!empty($checkbox_subs)) ? '<p><strong>Checkbox</strong> : '.$checkbox_subs .'</p>' : '';
$message .= (!empty($spFullname)) ? '<p><strong>User Name</strong> : '.$spFullname .'</p>' : '';
$message .= (!empty($spEmail)) ? '<p><strong>User Email</strong> : '.$spEmail .'</p>' : '';
$message .= (!empty($spCompany)) ? '<p><strong>Company</strong> : ' . $spCompany .' </p>' : '';
$message .= (!empty($spMsg)) ? '<p><strong>User Message</strong> : '.$spMsg .'</p>' : '';
$message .= (!empty($checkbox_sp)) ? '<p><strong>Checkbox</strong> : '.$checkbox_sp .'</p>' : '';
$message .= (!empty($url)) ? '<p><strong>Url:</strong> : '.$url .'</p>' : '';
$message .= '</body></html>';
$send_mail = mail($to, $subject, $message, $headers);
echo $send_mail;
if($send_mail) {
$data = get_field('success_message', 'option');
wp_send_json_success($data, 200);
}
return $msg;
die();
}
AJAX:
jQuery('.submit').on('click', function(e) {
e.preventDefault();
// All data from form
var str = $(this).closest('form').serialize();
$("#contact-form input:checkbox:not(:checked)").each(function(e){
str += "&"+this.name+'=false';
});
// Vars
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var msg = jQuery('#msg').val();
var subj = jQuery('#subj').val();
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
jQuery.ajax({
type: "post",
url: ajaxactionurl,
data: "action=send_email&" + str + "&url=" + page_url,
dataType: 'json',
success: function (response) {
jQuery('#contact-form input').val('');
jQuery('#contact-form textarea').val('');
jQuery('.submit').text('Thank you!');
console.log(response.data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
});

Your AJAX Call should only return JSON and should not return anything else, so making following changes.
$send_mail = mail($to, $subject, $message, $headers);
//echo $send_mail; Comment this, it is not required
if($send_mail) {
$data = get_field('success_message', 'option');
wp_send_json_success( array('data' => $data ) , 200); //Return as array.
}
//return $msg; Comment this as well.
die();
In your AJAX Callback of JS, you will get the data where you are using console.log(response.data);

Related

Can't get the name from $NAME

I have a subscription form that contains tow variables $name and $email.
and I get only the $email from the form.I can't get the $name.
I have tried all I knew to fix it, the form is fully working, it sends the code to email and writes to the file,just doesn't give me name!
Thanks.
This is the PHP code:
<?php
header('content-type: application/json');
$o = new stdClass();
$o->status = 'success';
echo json_encode($o);
$Length = 9;
$RandomString = substr(str_shuffle(md5(time())), 0, $Length);
$email = $_POST["email"];
$name = $_POST["author"];
$emailTo = 'info#praia.co.il';
$subject = 'הרשמה לרכישה קבוצתית פראיה ';
$body = "\n\nשם הלקוח: $name \n\nאימייל: $email \n\nקוד קופון: $RandomString";
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($emailTo, $subject, $body, $headers, $randomString);
$headers2 = "From: Praia <info#praia.co.il>" . "\r\n".
'Reply-To: '.$emailTo."\r\n" .
'Content-Type: text/html; charset=ISO-8859-1\r\n'.
'Return-Path: Praia <info#praia.co.il>\r\n'.
'X-Mailer: PHP/' . phpversion();
$message = '<html><body><center><div style="background:#f0f0f0; font-family:"almoni-tzar";>';
$message .= '<img src="http://praia.co.il/assets/img/logo.png" alt="logo" style="width:150px; height:150px;"></a><br />';
$message .= '<br />';
$message .= " שלום $name, אנו שמחים שהצטרפת לרכישה הקבוצתית של פראיה.</p>";
$message .= '<br>';
$message .= "$RandomString :קוד ההרשמה שלך לרכישה הוא ";
$message .= '<br />';
$message .= "קוד ההרשמה הינו חד פעמי*";
$message .= '<br />';
$message .= '<br />';
$message .= '<br />';
$message .= '<br />';
$message .= ' מעבר לאתר מעבר לתקנון';
$message .= '</div></center></body></html>';
$mailed = true;
if($mailed==true){
mail($email, "פראיה- הרשמה לרכישה קבוצתית.", $message , $headers2);
}else{
echo 'error';
}
if($mailed==true){
//file_put_contents("coupon.txt", $email. . $RandomString . PHP_EOL, FILE_APPEND);
file_put_contents("coupon.txt", $email . " " . $RandomString . "\r\n" , FILE_APPEND | LOCK_EX);
}else{
echo 'error';
}
?>
JS code:
/*
notifyMe jQuery Plugin v1.0.0
Copyright (c)2014 Sergey Serafimovich
Licensed under The MIT License.
*/
(function(e) {
e.fn.notifyMe = function(t) {
var r = e(this);
var i = e(this).find("input[name=email]");
var s = e(this).attr("action");
var o = e(this).find(".note");
e(this).on("submit", function(t) {
t.preventDefault();
var h = i.val();
var p = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (p.test(h)) {
$(".message").removeClass("error bad-email success-full");
$(".message").hide().html('').fadeIn();
o.show();
e.ajax({
type: "POST",
url: s,
data: {
email: h
},
dataType: "json",
error: function(e) {
o.hide();
if (e.status == 404) {
$(".message").hide().html('<p class="notify-valid style="font-family:almoni-tzar;"> .אופס, נראה שמשהו השתבש! נסה מאוחר יותר <i class="icon ion-close-round"></i></p>').slideDown();
} else {
$(".message").hide().html('<p class="notify-valid style="font-family:almoni-tzar;"> .אופס, נראה שמשהו השתבש! נסה מאוחר יותר <i class="icon ion-close-round"></i></p>').fadeIn();
}
}
}).done(function(e) {
o.hide();
if (e.status == "success") {
$(".message").removeClass("bad-email").addClass("success-full");
$(".message").hide().html('<p class="notify-valid" style="font-family:almoni-tzar;"> .נרשמת בהצלחה לרכישה הקבוצתית תעודכן בהמשך <i class="icon ion-checkmark-round"></i></p>').fadeIn();
} else {
if (e.type == "ValidationError") {
$(".message").hide().html('<p class="notify-valid style="font-family:almoni-tzar;"> .כתובת המייל נראית לא חוקית, נא הזן כתובת חדשה <i class="icon ion-close-round"></i></p>').fadeIn();
} else {
$(".message").hide().html('<p class="notify-valid style="font-family:almoni-tzar;"> .אופס, נראה שמשהו השתבש! נסה מאוחר יותר <i class="icon ion-close-round"></i></p>').fadeIn();
}
}
})
} else {
$(".message").addClass("bad-email").removeClass("success-full");
$(".message").hide().html('<p class="notify-valid" style="font-family:almoni-tzar;"> .כתובת המייל אינה חוקית נא נסה שנית <i class="icon ion-close-round"></i></p>').fadeIn();
o.hide();
}
// Reset and hide all messages on .keyup()
$("#notifyMe input").keyup(function() {
$(".message").fadeOut();
});
})
}
})(jQuery)
Your ajax call is only sending the mail. You should change
var i = e(this).find("input[name=email]");
...
data: {
email: h
},
To something along the lines of:
var i = e(this).find("input[name=email]");
var authorValue = e(this).find("input[name=author]");
...
data: {
email: h,
author: authorValue
},
While adding on your list above the

Send email according to input select value

I need to make changes to an existing form by adding a dropdown menu where I will have two inputs and their values. The purpose is to send the form to recipient_one if Address 1 is selected or to recipient_two when Address 2 is selected. Address 1 needs to be the default value when nothing is selected.
Here is just the added HTML:
<form method="post" action="./index.php" enctype="multipart/form-data">
<fieldset class="elist">
<legend>Select shop:</legend>
<select name="shop">
<option name="address-chosen" value="Tammsaare" >Tammsaare</option>
<option name="address-chosen" value="Ülemiste" >Ülemiste</option>
</select>
</fieldset>
</form>
and the PHP:
$action = isset($_POST['action']) ? $_POST['action'] : null;
$page = null;
$pages = array('info', 'en');
if( isset($_GET['page']) && in_array($_GET['page'], $pages) ) {
$page = $_GET['page'];
}
if( !in_array($page, $pages) ) {
$page = '';
}
$mail_sent = false;
if( $action == 'add' ) {
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip = $_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
$message = '';
$message .= 'Name: '.safe($_POST['name'])."\r\n";
$message .= 'E-mail: '.safe($_POST['email'])."\r\n";
$message .= 'Phone: '.safe($_POST['telephone'])."\r\n";
$message .= 'Mark: '.safe($_POST['mark'])."\r\n";
$message .= 'Model: '.safe($_POST['model'])."\r\n";
$message .= 'Shop: '.safe($_POST['address-chosen'])."\r\n";
$message .= "Wants newsletter: ".$soovib_uudiskirja = isset($_POST['newsletter']) ? "Yes" : "No";
$message .= "\r\n";
$message .= "\r\n";
$message .= "\r\n";
$message .= 'Aeg: '.date('d.m.Y H:i')."\r\n";
$message .= 'IP: '.$ip."\r\n";
$mail_data = array(
'to_email' => 'email#mail.com',
'from_email' => 'email#mail.com',
'from_name' => 'Stock Cars',
'subject' => 'Reservation',
'message' => $message,
);
mail_send($mail_data);
$mail_sent = true;
}
function safe( $name ) {
return( str_ireplace(array( "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:" ), "", $name ) );
}
function mail_send($arr)
{
if (!isset($arr['to_email'], $arr['from_email'], $arr['subject'], $arr['message'])) {
throw new HelperException('mail(); not all parameters provided.');
}
$to = empty($arr['to_name']) ? $arr['to_email'] : '"' . mb_encode_mimeheader($arr['to_name']) . '" <' . $arr['to_email'] . '>';
$from = empty($arr['from_name']) ? $arr['from_email'] : '"' . mb_encode_mimeheader($arr['from_name']) . '" <' . $arr['from_email'] . '>';
$headers = array
(
'MIME-Version: 1.0',
'Content-Type: text/plain; charset="UTF-8";',
'Content-Transfer-Encoding: 7bit',
'Date: ' . date('r', $_SERVER['REQUEST_TIME']),
'Message-ID: <' . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
'X-Mailer: PHP v' . phpversion(),
'X-Originating-IP: ' . $_SERVER['SERVER_ADDR'],
);
mail($to, '=?UTF-8?B?' . base64_encode($arr['subject']) . '?=', $arr['message'], implode("\n", $headers));}
if (isset($_GET['page'])) {}
So the question is how do I reconstruct the array?
Set the email variable based on the form value:
//default is email 1
$email='email#mail.com';
if(isset($_POST['shop']) && $_POST['shop']=='Ülemiste') {$email='email2#mail2.com';}
$mail_data = array(
'to_email' => $email,
'from_email' => $email,
'from_name' => 'Stock cars',
'subject' => 'Reservation',
'message' => $message,
);
edited as per your edit - not sure how the umlaut will effect things though

PHP mail function returning utf8 errors in hotmail/outlook

Lately I've been having some big problems with sending e-mails through my website, as it seems to always show major encoding differences on the e-mail clients. As it almost always works on Gmail and others, on Hotmail/Outlook there's always an UTF8 error in the title/subject of the message. I tried encoding/decoding several variables to keep that from happening, but every solution ends up leaving an error.
Here's the function to send the e-mails via form:
function enviarEmail($nomeRemetente = '', $emailRemetente = 'email#dominio.com', $emailDestinatario = 'email#dominio.com', $emailResposta = 'email#dominio.com', $assunto = '', $campos = array(), $dados = array(), $customMsg = false, $mensagemHTML = '')
{
$retorno = true;
$quebra_linha = "\n";
if (PHP_OS == 'Linux') {
$quebra_linha = "\n";
} elseif (PHP_OS == 'WINNT') {
$quebra_linha = "\r\n";
}
if (!$customMsg) {
$mensagemHTML = '<table width="490" border="0" cellpadding="0" cellspacing="6">
<tr>
<td colspan="2">
<p style="font-size: 14px; font-family: Arial, Helvetica, sans-serif; color: #A93118;">..: ' . $assunto . '</p>
<p>Formulário preenchido em ' . date('d/m/Y') . ' as ' . date('H:i') . '</p>
</td>
</tr>
';
$qtde = count($campos);
for ($i = 0; $i < $qtde; $i++) {
$mensagemHTML .= '
<tr>
<td align="right"><strong>' . $campos[$i] . ': </strong></td>
<td>' . $dados[$i] . '</td>
</tr>
';
}
$mensagemHTML .= '</table>';
}
$headers = implode($quebra_linha, #
array('MIME-Version: 1.1', #
'Content-type: text/html; charset=utf-8', #
'From: ' . html_entity_decode($nomeRemetente) . ' <' . $emailRemetente . '>', #
'Return-Path: ' . utf8_decode($nomeRemetente) . ' <' . $emailRemetente . '>', #
'Reply-To: ' . $emailResposta, #
'Subject: ' . $assunto, #
'X-Priority: 3'
));
$emailDestinatario = is_array($emailDestinatario) ? $emailDestinatario : array($emailDestinatario);
foreach ($emailDestinatario as $emailDestino) {
mail($emailDestino, $assunto, $mensagemHTML, $headers) or $retorno = false;// die('Erro no servidor!');
}
return $retorno;
}
And this function is called here:
function enviarContato()
{
$nomeRemetente = PROJECT_SHORT_TITLE;
$emailRemetente = $emailResposta = PROJECT_EMAIL;
$subject = 'Contato no site Modelo Site Rápido - ' . date('d/m/Y H:i:s');
$emailDestinatario = array('programacao#monge.com.br'/*, PROJECT_EMAIL*/);
$campos = array();
$dados = array();
$campos[] = 'Nome';
$dados[] = isset($_REQUEST['contatoNome']) ? $_REQUEST['contatoNome'] : '';
$campos[] = 'Email';
$emailResposta = $dados[] = isset($_REQUEST['contatoEmail']) ? $_REQUEST['contatoEmail'] : '';
$campos[] = 'Telefone';
$dados[] = isset($_REQUEST['contatoTelCel']) ? htmlspecialchars($_REQUEST['contatoTelCel'], ENT_COMPAT, 'UTF-8') : '';
$campos[] = 'Mensagem';
$dados[] = isset($_REQUEST['contatoMensagem']) ? nl2br(stripcslashes($_REQUEST['contatoMensagem'])) : '';
$conf = enviarEmail($nomeRemetente, $emailRemetente, $emailDestinatario, $emailResposta, utf8_decode($subject), $campos, $dados);
$link = 'http://' . PROJECT_URL . '/contato.php'; // usado sem mod_rewrite
if (isset($MG_MR_Settings['active']) && $MG_MR_Settings['active']) {
$link = 'http://' . PROJECT_URL . '/contato'; // usado com mod_rewrite
}
if ($conf) {
echo "<script type='text/javascript'>";
echo "alert('Contato enviado com sucesso!');";
echo "document.location.replace('$link');";
echo "</script>";
die();
} else {
echo "<script type='text/javascript'>";
echo "alert('Erro ao enviar contato, contate o administrador.');";
echo "document.location.replace('$link');";
echo "</script>";
die();
}
}
$msgContato = '';
if (!empty($_POST['SubmitContato'])) {
$msgContato = enviarContato();
}
The problem that this is returning on Hotmail/Outlook is like this:
Contato no site Centro Estético Bela - 17/12/2013 11:48:53
177.97.93.251
It works well on Gmail. If anyone can point to the right direction I would greatly appreciate it. Please ask for any info that might help you solve this, hope it seems clear enough.
Thank you in advance.
Good day:
i´m use this subject
$subject = "=?UTF-8?B?" . base64_encode('Confirmación de Compra (' . $order_id .")" ) . "?=";
in your case:
$subject = "=?UTF-8?B?" . base64_encode('Contato no site Modelo Site Rápido - ' . date('d/m/Y H:i:s') ) . "?=";

My PHP form will not send to multiple users

Hi I have a php form that works perfectly when it sends an email to one person but when I add another email address it doesn't send an email to either address. I have been looking on php sites but can't see why my form is now refusing to email once the second email address is added.
<?php
function isRequestSet( $name ) {
if ( isset ( $_REQUEST[$name] ) ) {
return ( $_REQUEST[$name] != "" ) ;
}
return false;
}
$name = "";
if ( isRequestSet('name' ) ) {
$name = $_REQUEST['name'];
}
$number = "";
if ( isRequestSet('number') ) {
$number = $_REQUEST['number'];
}
$email = "";
if ( isRequestSet( 'email' ) ) {
$email = $_REQUEST['email'];
}
$postcode = "";
if ( isRequestSet('postcode' ) ) {
$location = $_REQEUST['postcode'];
}
$how_did_you_hear_about_us = array();
if ( isset( $_REQUEST['how_did_you_hear_about_us'] ) ) {
$how_did_you_hear_about_us = $_REQUEST['how_did_you_hear_about_us'];
}
$message = "";
if ( isRequestSet('message' ) ) {
$location = $_REQEUST['message'];
}
$apartment_price_range = array();
if ( isset( $_REQUEST['apartment_price_range'] ) ) {
$apartment_price_range = $_REQUEST['apartment_price_range'];
}
$url = "";{
$url = $_REQUEST['url'];
}
$property = "";{
$property = $_REQUEST['property'];
}
if ( ($name !="") && ($number != "") && ($email != "") && ($isspam !="yes") ) {
$to = 'name#email.com,name#email2.com';
$from = $to;
$headers = 'From: ' . $to . "\n" .
'Reply-To: ' . $to . "\n";
$vars = array( 'name' , 'number' , 'email' , 'postcode' , 'message' ) ;
$message = "-----------\n" ;
foreach ( $vars as $v ) {
$value = $_REQUEST[$v];
$message .= "$v:\t$value\n";
}
$message .= "-----------\n" ;
$message .= "\nHow did you hear about apartments?:\n" ;
foreach ( $how_did_you_hear_about_us as $how_did_you_hear_about_us ) {
$message .= "$how_did_you_hear_about_us\n" ;
}
$message .= "-----------\n" ;
$message .= "\nApartment price range:\n" ;
foreach ( $apartment_price_range as $apartment_price_range ) {
$message .= "$apartment_price_range\n" ;
}
$subject = "From: $name <$email>";
mail( $to , $subject , $message , $headers, "-f $from" );
$confirm = true;
//redirect to the 'thank you' page
header("Location:http://website.com/file/thankyou.php");
} else {
$confirm = false;
}
?>
Most likely it is because you use multiple addresses for From and Reply-to fields:
$to = 'name#email.com,name#email2.com';
$from = $to;
Change it to use either first email or something like your-service-name#you-domain-name.com
Use only one address for From and Reply-To.
$from = 'me#my-domain.com';
$headers = 'From: ' . $from . "\n" .
'Reply-To: ' . $from . "\n";
"In the line below you should break the $to field into an array.
mail( $to , $subject , $message , $headers, "-f $from" );
For example
$address_array = split(",", $to);
foreach($address_array as $address)
{
mail( $address, $subject , $message , $headers, "-f $from" );
}
This allows for you $to string to contain as many emails as desired.
N.b if you wish to skip the split line just store the $to as an array
$to = array("name#email.com","name#email2.com");
make your email part into a function.
will much more easier for you to pass the email address.
function email_to_user($email_address){
$to = $email_address;
<rest of the codes>
}
and you can easily pass the email address
email_to_user(name1#mail.com);
email_to_user(name2#mail.com);

PHP Form Checkboxes

How do I get the values of php checkboxes in a form to show when emailed to the recipient?
I am learning how to use php but I can't figure this one out with the form i have generated.
Below is the checkbox code from the form itself:
<input type="checkbox" value="Please send me a Travel Planner" name="options[]">
<input type="checkbox" value="Please send me a Visitor Map" name="options[]" />
<input type="checkbox" value="Please sign me up for the email newsletter" name="options[]" />
Now here's the form code from the feedback page that processes it:
#<?php
// ------------- CONFIGURABLE SECTION ------------------------
// $mailto - set to the email address you want the form
// sent to, eg
//$mailto = "youremailaddress#example.com" ;
$mailto = 'xxxxx#xxxxxxxxx.com' ;
// $subject - set to the Subject line of the email, eg
//$subject = "Feedback Form" ;
$subject = "Request For Visitor Guide" ;
// the pages to be displayed, eg
//$formurl = "http://www.example.com/feedback.html" ;
//$errorurl = "http://www.example.com/error.html" ;
//$thankyouurl = "http://www.example.com/thankyou.html" ;
$formurl = "http://www.example.com/requestform_mtg.php" ;
$errorurl = "http://www.example.com/error.php" ;
$thankyouurl = "http://www.example.com/thankyou.php" ;
$email_is_required = 1;
$name_is_required = 1;
$address_is_required = 1;
$contactname_is_required = 1;
$city_is_required = 1;
$zip_is_required = 1;
$phone_is_required = 1;
$uself = 0;
$use_envsender = 0;
$use_webmaster_email_for_from = 1;
$use_utf8 = 1;
// -------------------- END OF CONFIGURABLE SECTION ---------------
$headersep = (!isset( $uself ) || ($uself == 0)) ? "\r\n" : "\n" ;
$content_type = (!isset( $use_utf8 ) || ($use_utf8 == 0)) ? 'Content-Type: text/plain; charset="iso-8859-1"' : 'Content-Type: text/plain; charset="utf-8"' ;
if (!isset( $use_envsender )) { $use_envsender = 0 ; }
$envsender = "-f$mailto" ;
$name = $_POST['name'] ;
$contactname = $_POST['contactname'] ;
$title = $_POST['title'] ;
$email = $_POST['email'] ;
$address = $_POST['address'] ;
$city = $_POST['city'] ;
$state = $_POST['state'] ;
$zip = $_POST['zip'] ;
$fax = $_POST['fax'] ;
$phone = $_POST['phone'] ;
$mtgname = $_POST['mtgname'] ;
$dates = $_POST['dates'] ;
$attendance = $_POST['attendance'] ;
$guestroom = $_POST['guestroom'] ;
$mtgroom = $_POST['mtgroom'] ;
$timeframe = $_POST['timeframe'] ;
$options = $_POST['options'] ;
$comments = $_POST['comments'] ;
$http_referrer = getenv( "HTTP_REFERER" );
if (!isset($_POST['email'])) {
header( "Location: $formurl" );
exit ;
}
if (($email_is_required && (empty($email) || !ereg("#", $email))) || ($name_is_required && empty($name)) || ($address_is_required && empty($address)) || ($contactname_is_required && empty($contactname)) || ($city_is_required && empty($city)) || ($zip_is_required && empty($zip)) || ($phone_is_required && empty($phone))) {
header( "Location: $errorurl" );
exit ;
}
if ( ereg( "[\r\n]", $name ) || ereg( "[\r\n]", $email ) || ereg( "[\r\n]", $address ) || ereg( "[\r\n]", $contactname ) ) {
header( "Location: $errorurl" );
exit ;
}
if (empty($email)) {
$email = $mailto ;
}
$fromemail = (!isset( $use_webmaster_email_for_from ) || ($use_webmaster_email_for_from == 0)) ? $email : $mailto ;
if (get_magic_quotes_gpc()) {
$comments = stripslashes( $comments );
}
$messageproper =
"This message was sent from:\n" .
"$http_referrer\n" .
"------------------------------------------------------------\n" .
"Organization Name: $name\n" .
"Contact Name: $contactname\n" .
"Email of sender: $email\n" .
"Address of sender: $address\n" .
"City of sender: $city\n" .
"State of sender: $state\n" .
"Zip Code of sender: $zip\n" .
"Fax of sender: $fax\n" .
"Phone of sender: $phone\n" .
"Meeting Name: $mtgname\n" .
"Preferred Dates: $dates\n" .
"Expected Attendance: $attendance\n" .
"Guest Rooms: $guestroom\n" .
"Largest Meeting Room Needed: $mtgroom\n" .
"Decision Timeframe: $timeframe\n" .
"Options: $options\n" .
"------------------------- COMMENTS -------------------------\n\n" .
$comments .
"\n\n------------------------------------------------------------\n" ;
$headers =
"From: \"$name\" <$fromemail>" . $headersep . "Reply-To: \"$name\" <$email>" . $headersep . "X-Mailer: chfeedback.php 2.13.0" .
$headersep . 'MIME-Version: 1.0' . $headersep . $content_type ;
if ($use_envsender) {
mail($mailto, $subject, $messageproper, $headers, $envsender );
}
else {
mail($mailto, $subject, $messageproper, $headers );
}
header( "Location: $thankyouurl" );
exit ;
?>
All I get via email for the checkboxes is "array".
Thanks
Update:
Just noticed I get these errors if I DON'T select a checkbox and submit:
Warning: implode() [function.implode]: Invalid arguments passed in /home/content/o/l/t/oltvcb/html/feedback_mtg.php on line 148
Warning: Cannot modify header information - headers already sent by (output started at /home/content/o/l/t/oltvcb/html/feedback_mtg.php:148) in /home/content/o/l/t/oltvcb/html/feedback_mtg.php on line 162
I did notice that the form data actually came through in my email.
$options is an array. Try imploding it.
$options = implode(', ', $options);
Checkboxes are treated as an array when they are submitted.
foreach($options as $option) {
print $option."\n";
}
or
print implode("\n", $options);
Here's a suggestion. Instead of this:
"Options: $options\n" .
Try this:
"Options:".implode("\n",$options)."\n".
There's always the possibility that no array of $options will exist (no check boxes were checked). In this case, you can do something like:
"Options:".(isset($options) ? implode("\n",$options) : "")."\n".
$options = join(', ', $_POST['options']);
First, you need to get rid of your "[ ]" in the name of your variable for the HTML checkboxes.
If you name it "options" when it is submitted to the processing page it comes through as an array.
From that point, you now have an array of the values selected.
$_POST['options']

Categories