Form redirection on configuration PHP page - php

I have a completely functional Form that sends mail as it should and all BUT for some reason, when I (try to) submit my message, instead of showing the success or error alert under the form, it opens the sendmail.php page with the messages, without any CSS... It's been 4 days and I'm going crazy. I'm sure it's actually a stupid typo or something but I can't find it, please help.
Screen of the "Success/Alert" display
Here's my sendmail.php:
<?php
$sendto = 'my#email.com';
$subject = 'Message de votre site';
$errormessage = 'Ah, vous avez oublié quelques informations. Réessayez ? ';
$thanks = "Merci pour votre message ! On vous répond aussi vite que possible. ";
$honeypot = "Vous êtes tombé dans le piège ! Si vous êtes humain.e, recommencez ! ";
$emptyname = 'Quel est votre nom ? ';
$emptyemail = 'Quelle est votre adresse mail ? ';
$emptymessage = 'Et votre message ? ';
$alertname = 'Utilisez uniquement un alphabet standard. ';
$alertemail = 'Entrez ce format de mail : <i>name#example.com</i>. ';
$alertmessage = "Vérifiez que vous n 'avez utilisé aucun caractère spécial. ";
$alert = '';
$pass = 0;
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
if ( empty($_REQUEST['last']) ) {
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
$alert .= "<script>jQuery(\"#name\").addClass(\"error\");</script>";
} elseif ( preg_match( "/[][{}()*+?.\\^$|]/", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
$alert .= "<script>jQuery(\"#email\").addClass(\"error\");</script>";
} elseif ( !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
$alert .= "<script>jQuery(\"#message\").addClass(\"error\");</script>";
} elseif ( preg_match( "/[][{}()*+?\\^$|]/", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
if ( $pass==1 ) {
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\"); </script>";
echo "<script>$(\".result .alert\").addClass('alert-danger').removeClass('alert-success'); </script>";
echo $errormessage;
echo $alert;
} elseif (isset($_REQUEST['message'])) {
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
mail($sendto, $subject, $message, $header);
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\");$('#contactForm')[0].reset();</script>";
echo "<script>$(\".result .alert\").addClass('alert-success').removeClass('alert-danger'); </script>";
echo $thanks;
echo "<script>jQuery(\"#name\").removeClass(\"error\");jQuery(\"#email\").removeClass(\"error\");jQuery(\"#message\").removeClass(\"error\");</script>";
echo "<script>$(\".result .alert\").delay(4000).hide(\"fast\");</script>";
die();
echo "<br/><br/>" . $message;
}
} else {
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\");</script>";
echo $honeypot;
}
?>
And HTML:
<form class="form-inline flowuplabels" role="form" method="post" autocomplete="off" id="contactForm" action="js/sendmail.php">
<div class="form-group fl_wrap">
<label class="fl_label" for="name">Nom :</label>
<input type="text" name="name" value="" id="name" class="form-control fl_input" required>
</div>
<div class="form-group fl_wrap">
<label class="fl_label" for="email">Email :</label>
<input type="text" name="email" value="" id="email" class="form-control fl_input" required>
</div>
<span class="form-group fl_wrap honeypot">
<label class="fl_label" for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" class="form-control fl_input">
</span>
<div class="form-group fl_wrap">
<label class="fl_label" for="message">Message :</label>
<textarea type="text" name="message" value="" id="message" class="materialize-textarea" required></textarea>
</div>
<div class="form-group">
<button type="submit" value="Send" id="submit" class="btn btn-block">Envoyer</button>
</div>
<div id="form-alert" class="form-group">
<div class="result">
<div class="alert"></div>
</div>
</div>
</form>
As some asked. The HTML is on the index page and the sendmail.php is an independent page.
And this is where the success/alert message is supposed to appear :
Form in website

Related

WordPress custom Contact Form in Bootstrap modal is not showing validation & submission response

For my WordPress (v5.5.1) I am using Bootstrap and built a Custom Contact Form in Bootstrap Modal with below HTML (followed this tutorial: https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/).
<form id="contact-form" action="<?php echo get_site_url(); ?>" method="post">
<div class="modal-body">
<?php echo $response; ?>
<div class="form-group">
<input class="form-control my-2" type="text" name="message_name" size="50" placeholder="Your full name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input class="form-control my-2" type="email" name="message_email" size="50" placeholder="Email address" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input class="form-control my-2" type="tel" name="message_tel" size="50" placeholder="Country code, Phone number" value="<?php echo esc_attr($_POST['message_tel']); ?>">
<textarea class="form-control my-2" name="message_text" rows="2" placeholder="Your message" value="<?php echo esc_attr($_POST['message_text']); ?>"></textarea>
<input class="form-control my-2" type="text" name="message_human" placeholder="Human check: Enter 2">
<input type="hidden" name="message_url" value="<?php the_permalink(); ?>">
<input type="hidden" name="message_page" value="<?php the_title(); ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="submitted" value="1">
<button type="submit" value="Submit" class="btn btn-search form-control">Send Enquiry</button>
</div>
Below the function to validate the Forms & show responses while Form submission:
function validateform() {
//response generation function
$response = "";
//function to generate response
function contact_g_form_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
}
//response messages
$not_human = "Enter current year in numbers.";
$missing_content = "Missing something.";
$email_invalid = "Check your Email address.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! We got your enquiry.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$fromEmail = $name . '<' . $email . '>';
$tel = $_POST['message_tel'];
$text = $_POST['message_text'];
$url = $_POST['message_url'];
$page = $_POST['message_page'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = '[General Enquiry] ' . $name . ' | Phone Number:' . $tel;
$headers = 'From: ' . $fromEmail . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$message = '<html><body><h1>New general enquiry from ' . $name . '!</h1>'
. '<p>Email: ' . $email . '</p>'
. '<p>Phone Number: ' . $tel . '</P>'
. '<p>Inquiry: ' . $text . '</P>'
. '<p>From page: <b>' . $page . '</b></P>'
. '<p>Page URL: ' . $url . '</p>'
. '</body></html>';
if (!$human == 0) {
if ($human != 2) {
contact_g_form_response("error", $not_human); //not human!
} else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
contact_g_form_response("error", $email_invalid);
} else { //email is valid
//validate presence of name, phone number
if (empty($name) || empty($tel)) {
contact_g_form_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to, $subject, $message, implode("\r\n", $headers)); //mail to admin - striptags removing formatting
// $sent2 = wp_mail($email, $subject, $body, $headers); //mail to visitor
// if ($sent || $sent2) {
if ($sent) {
contact_g_form_response("success", $message_sent); //message sent!
} else {
contact_g_form_response("error", $message_unsent); //message wasn't sent
}
}
}
}
} else if ($_POST['submitted']) {
contact_g_form_response("error", $missing_content);
}
}
In the earlier versions of WordPress the email was being sent without validation, with v5.5.1 upgrade, the Modal is closing without any validation and the email is also not being sent.
You Just Need To replace this:
<form id="contact-form" action="<?php echo get_site_url();?>" method="post">
With This:
<form id="contact-form" method="post">
Because You are displaying the error on the same page but on click of the submit button the action is taking you to a specific url and that's the reason the validations are not shown.
And This:
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
With This also:
if ($type == "success") {
$response = $message;
echo $response;
} else {
$response = $message;
echo $response;
}

Redirect to separate succes page after form submit

I am using bootstrap and have a form I've been using for a while now. It shows the message "Verzonden!" on the same page if the form has been submitted succesfully. now this has to be altered to redirect to a new succes page after the form is submitted.
this is the html I am using
<form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
<div class="form-group">
<div class="controls">
<input type="text" id="name" class="form-control" placeholder="Naam & Voornaam" required data-error="Gelieve uw naam in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Gelieve uw email adres in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="phone" class="form-control" placeholder="Telefoonnummer" required data-error="Gelieve uw telefoonnummer in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="msg_subject" class="form-control" placeholder="Onderwerp" required data-error="Gelieve een onderwerp in te vullen.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="7" placeholder="Bericht" class="form-control" required data-error="Gelieve uw bericht in te vullen."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-success"></i>Verzend!</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
This is the php I am using:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Gelieve uw naam in te vullen.";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Gelieve uw email adres in te vullen.";
} else {
$email = $_POST["email"];
}
// PHONE
if (empty($_POST["phone"])) {
$errorMSG .= "Gelieve uw telefoonnummer in te vullen.";
} else {
$phone = $_POST["phone"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Gelieve een onderwerp in te vullen.";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Gelieve een bericht in te vullen";
} else {
$message = $_POST["message"];
}
//Add your email here
$EmailTo = "e-mail address";
$Subject = "Nieuw bericht van website";
// prepare email body text
$Body = "";
$Body .= "Naam: ";
$Body .= "\n";
$Body .= $name;
$Body .= "\n";
$Body .= "\n";
$Body .= "Email: ";
$Body .= "\n";
$Body .= $email;
$Body .= "\n";
$Body .= "\n";
$Body .= "Telefoonnummer: ";
$Body .= "\n";
$Body .= $phone;
$Body .= "\n";
$Body .= "\n";
$Body .= "Onderwerp: ";
$Body .= "\n";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "\n";
$Body .= "Bericht: ";
$Body .= "\n";
$Body .= $message;
$Body .= "\n";
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "Verzonden!";
}else{
if($errorMSG == ""){
echo "Er is een fout opgetreden, probeert u aub opnieuw.";
} else {
echo $errorMSG;
}
}
?>
You have to redirect the user to a new page using the php header function:
// redirect to success page
if ($success && $errorMSG == ""){
header('Location: http://www.example.com/success-page.php');
}else{
if($errorMSG == ""){
echo "Er is een fout opgetreden, probeert u aub opnieuw.";
} else {
echo $errorMSG;
}
}
IMPORTANT NOTE
Never print or echo anything before the header() redirect call or else it will not redirect the user.
Read the reference here:
http://php.net/manual/en/function.header.php
UPDATE
// redirect to success page
if ($success && $errorMSG == ""){
header('Location: http://www.example.com/success-page.php');
}else{
if($errorMSG == ""){
header('Location: http://www.example.com/success-page.php');
} else {
echo $errorMSG;
}
}
also added condition for if($errorMSG == "")
Also
It is a good practice to add the action attribute in your form like so:
<form action="path-to-your-processing-script.php">
If you don't provide that it will submit the form on the same page but still you should give it anyway.

PHP multiple fields contact form issue

I've got a problem with a PHP contact form (yes, classic issue I know).
I'm pretty new in PHP and I don't find what is broken in my code.
Here is the PHP:
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'contact#must-assurances.com';
$clientEmail = addslashes(trim($_POST['email']));
$name = addslashes(trim($_POST['name']));
$entreprise = addslashes(trim($_POST['entreprise']));
$message = addslashes(trim($_POST['message']));
$antispam = addslashes(trim($_POST['antispam']));
$jesuis = addslashes(trim($_POST['jesuis']));
$tel = addslashes(trim($_POST['tel']));
$siren = addslashes(trim($_POST['siren']));
$array = array('emailMessage' => '', 'entrepriseMessage' => '', 'messageMessage' => '', 'antispamMessage' => '', 'jesuisMessage' =>'', 'nameMessage' =>'', 'telMessage' =>'', 'sirenMessage' =>'' );
if($siren == '') {
$array['sirenMessage'] = 'SIREN/SIRET invalide';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Email invalide';
}
if($name == '') {
$array['nameMessage'] = 'Nom manquant';
}
if($entreprise == '') {
$array['entrepriseMessage'] = 'Entreprise manquante';
}
if($tel == '') {
$array['telMessage'] = 'Numéro de téléphone manquant';
}
if($siren == '') {
$array['sirenMessage'] = 'SIREN/SIRET invalide';
}
if($message == '') {
$array['messageMessage'] = 'Message manquant';
}
if($antispam != '12') {
$array['antispamMessage'] = 'Mauvaise réponse';
}
if($jesuis == '') {
$array['jesuisMessage'] = 'Merci de préciser si vous êtes une entreprise, un courtier, un investisseur, un professionnel ou autre';
}
if(isEmail($clientEmail) && $entreprise != '' && $message != '' && $antispam == '12' && $jesuis != '' && $name !='' && $tel !='' && $siren!='') {
// Send email
$message = "Je suis un(e) ".$jesuis."\n \n ".$message."\n \n ".$name."\n \n ".$tel."\n \n ".$entreprise."\n \n ".$siren;
$headers = "From: " . $clientEmail . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail .
$headers = array("Content-Type: text/html; charset=UTF-8");
mail($emailTo, $entreprise . " (Formulaire inscription distributeur MUST Assurances)", $message, $headers);
}
echo json_encode($array);
}
?>
And here the HTML snippet:
<form role="form" action="contact-mia.php" method="post" accept-charset='UTF-8'>
<div class="form-group col-md-3">
<label for="name">Votre nom :</label>
<input type="text" name="name" placeholder="Votre nom..." class="contact-name form-control" id="name">
</div>
<div class="form-group col-md-3">
<label for="email">Votre adresse e-mail :</label>
<input type="text" name="email" placeholder="Email..." class="contact-email form-control" id="email">
</div>
<div class="form-group col-md-3">
<label for="name">Votre numéro de téléphone :</label>
<input type="text" name="tel" placeholder="Numéro de téléphone..." class="contact-tel form-control" id="tel">
</div>
<div class="form-group col-md-3">
<label for="entreprise">Entreprise :</label>
<input type="text" name="entreprise" placeholder="Entreprise..." class="contact-entreprise form-control" id="entreprise">
</div>
<div class="col-md-6 form-group">
<label for="jesuis">Je suis : </label>
<select class="form-control" name="jesuis" id="jesuis">
<option value="">Selectionnez...</option>
<option value="entreprise">Une entreprise</option>
<option value="courtier">Un courtier</option>
<option value="investisseur">Un investisseur</option>
<option value="professionnel">Un professionnel</option>
<option value="autre">Autre</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="entreprise">Numéro de SIREN/SIRET :</label>
<input type="text" name="siren" placeholder="SIREN/SIRET..." class="contact-siren form-control" id="siren">
</div>
<div class="col-md-12 form-group">
<label for="message">Message :</label>
<textarea name="message" placeholder="Message..." class="contact-message form-control" id="message"></textarea>
</div>
<div class="col-md-12 form-group">
<label for="antispam">Question Antispam : 7 + 5 = ?</label>
<input type="text" name="antispam" placeholder="Votre réponse..." class="contact-antispam form-control" id="antispam">
</div>
<div class="col-md-6 col-md-offset-3 form-group centered">
<button type="submit" class="btn">Envoyer</button>
</div>
</form>
Another issue about my $message syntax, here is the code:
$message = "Je suis un(e) ".$jesuis.'<br />'"Nom : ".$name.'<br />'"Telephone : ".$tel.'<br />'"SIREN : ".$siren.'<br />'"Entreprise : ".$entreprise.'<br />' "Message : ".$message;
Probably something wrong with the ' and " ?
Do you have any ideas?
Your PHP side has an error on the IF statement:
Take a further look at the lines containing: $headers
Your code:
if(isEmail($clientEmail) && $entreprise != '' && $message != '' && $antispam == '12' && $jesuis != '' && $name !='' && $tel !='' && $siren!='') {
// Send email
$message = "Je suis un(e) ".$jesuis."\n \n ".$message."\n \n ".$name."\n \n ".$tel."\n \n ".$entreprise."\n \n ".$siren;
$headers = "From: " . $clientEmail . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail .
$headers = array("Content-Type: text/html; charset=UTF-8");
mail($emailTo, $entreprise . " (Formulaire inscription distributeur MUST Assurances)", $message, $headers);
}
Corrected Code:
if(isEmail($clientEmail) && $entreprise != '' && $message != '' && $antispam == '12' && $jesuis != '' && $name !='' && $tel !='' && $siren!='') {
// Send email
$message = "Je suis un(e) ".$jesuis."\n \n ".$message."\n \n ".$name."\n \n ".$tel."\n \n ".$entreprise."\n \n ".$siren;
$headers = "From: " . $clientEmail . " <" . $clientEmail . ">\r\n";
$headers.= "Reply-To: " . $clientEmail . "\r\n";
$headers.= "Content-Type: text/html; charset=UTF-8\r\n";
// Wrap mail function in if statement to check if it worked
if (#mail($emailTo, $entreprise . " (Formulaire inscription distributeur MUST Assurances)", $message, $headers)) {
echo 'Successfully sent email';
} else {
echo 'Failed to send';
}
}
To help debug your code ensure your PHP errors are enabled, you can do this at the top of your PHP code using the following:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
I've got a new issue about my $message syntax.
Here is the code :
$message = "Je suis un(e) ".$jesuis.'<br />'"Nom : ".$name.'<br />'"Telephone : ".$tel.'<br />'"SIREN : ".$siren.'<br />'"Entreprise : ".$entreprise.'<br />' "Message : ".$message;
Probably something about the ' or " ?

Field in contact form

I'm new to PHP and have a problem with the following contact form:
The variable: $empresa = $_POST['empresa']; is not working... and I don't understand where the problem is. When I try to use it in the E-Mail sent, it just doesn't show up.
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
**This is the PHP I'm using: **
THANKS in advance
<?php
if(!$_POST) exit;
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$empresa = $_POST['empresa'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($comments) == '') {
echo '<div class="error_message">Has olvidado escribir tu mensaje.</div>';
exit();
}
if(trim($name) == '') {
echo '<div class="error_message">Tienes que poner un nombre.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Por favor pon tu dirección de e-mail, para poder ponernos en contacto contigo.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Dirección de e-mail inválida, inténtelo nuevamente.</div>';
exit();
}
$address = "mail#mail.com";
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
$received_body = "$name te ha contactado desde www.company.com " . PHP_EOL . PHP_EOL;
$received_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$received_reply = "Responder a $name $email o llamar al teléfono: $phone | Empresa: $empresa ";
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
$header = "From: $email" . PHP_EOL;
$header .= "Reply-To: $email" . PHP_EOL;
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>E-Mail enviado con éxito</h2>";
echo "<p>Gracias <strong>$name</strong>, tu mensaje ha sido enviado.</p>";
} else {
echo 'ERROR!';
}
MY form is here:
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="Nombre *">
</label>
<label for="empresa">
<input type="text" name="empresa" id="empresa" placeholder="Empresa *">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="E-Mail *">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="Número de teléfono">
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="Mensaje *"></textarea>
</label>
<p class="obligatorio"> * = Obligatorio</p>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Enviar">
</fieldset>
</form>
If all of your other post variables are working then it sounds like the $_POST['empresa'] variable is not making it to the php page. To debug your script you can either switch your form method to GET to see the query string in the browser url or use a tool like firebug which is a add on for firefox. You will get error on your php page when you switch to the GET method on your html form. Don't worry about that your are just trying to see if the empressa variable is being sent via the http Post request.
Ok your variable dump should show this based on the code your provided
array
'name' => string 'Larry' (length=5)
'empresa' => string 'Lane' (length=4)
'email' => string 'ok#yahoo.com' (length=12)
'phone' => string '123' (length=3)
'comments' => string 'ok' (length=2)
So empresa is making it to the page just fine. I did notice that you do not have an opening form tag for your form? You should have something like this with the names of your file in place of the ones I used for testing of course.
<form name="testform" action="testingpostvariables.php" method="POST">
Place echo $message; after your line of code in your php file
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
$echo message;
When I did it empresa showed up.
Ok put this code in seperate php file and test it so we can figure out why "empresa" is not showing up. I would also trying refreshing your browser before testing this file to make sure there is no bad cached results.
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="Nombre *">
</label>
<label for="empresa">
<input type="text" name="empresa" id="empresa" placeholder="Empresa *">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="E-Mail *">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="Número de teléfono">
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="Mensaje *"></textarea>
</label>
<p class="obligatorio"> * = Obligatorio</p>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Enviar">
</fieldset>
</form>
<?php
//debug
echo var_dump($_POST);
//debug
if(!$_POST){
echo "NO POST";
//exit;
}
else{
echo "POSTED";
}
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$empresa = $_POST['empresa'];
//impress is posting just fine
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($comments) == '') {
echo '<div class="error_message">Has olvidado escribir tu mensaje.</div>';
exit();
}
if(trim($name) == '') {
echo '<div class="error_message">Tienes que poner un nombre.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Por favor pon tu dirección de e-mail, para poder ponernos en contacto contigo.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Dirección de e-mail inválida, inténtelo nuevamente.</div>';
exit();
}
$address = "mail#mail.com";
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
//debug
//$empressa is still working fine
$received_body = "$name te ha contactado desde www.company.com " . PHP_EOL . PHP_EOL;
$received_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$received_reply = "Responder a $name $email o llamar al teléfono: $phone | Empresa: $empresa ";
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
echo $message;
$header = "From: $email" . PHP_EOL;
$header .= "Reply-To: $email" . PHP_EOL;
/*
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>E-Mail enviado con éxito</h2>";
echo "<p>Gracias <strong>$name</strong>, tu mensaje ha sido enviado.</p>";
} else {
echo 'ERROR!';
}
*/
This what my result looked like with the empresa value at the end(Lane is the empresa value I entered in the form).
POSTEDLarry te ha contactado desde www.company.com "This is a really long message ok lets see whats going on with this php code it is not sending the empresa variable" Responder a Larry mail#mail.com o llamar al teléfono: 12345678 | Empresa: Lane
Ok in your "custom.js" file you have the following line of code that could be causing some problems.
$.post(action, {
name: $('#name').val(),
empresa: $('#empresa').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(), //remove this comma
There should not be a comma after the last property value try removing that to see if you get the value of empresa from the jquery code. Try it and let me know i
I've solved the issue, by changing the word empresa with something else.
I think there was some sort of collision using this word.
Thanks so much for your help!

PHP form checkbox

I'm havig a really bad time with a checkbox contact form. Now If I click sent in my webpage I have this result in my email:
Email: whatever#whatever.com
Nombre: whatever
Le interessa: (THIS IS
CHECKBOX AND IT'S EMPTY VALUES. I WOULD LIKE TO TAKE THE CHOICES THAT THE USER MAKE)
Otros intereses: whatever
Thank you, I'll apreciate some help
HTML->
<form name="form-contact-us" id="form-contact-us">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="txtName">Name: </label>
<input type="text" placeholder="Name"
class="form-control required" id="txtName" name="txtName" />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="txtEmail">Email:</label>
<input type="text" placeholder="E-mail ID"
class="form-control required email" id="txtEmail" name="txtEmail" />
</div>
</div>
</div>
<label for="txtMessage">Información:</label><br>
***<input type="checkbox" id="web" name="check[]" value="Creación de web">
<label for="web">Creación de web</label><br>
<input type="checkbox" id="red" name="check[]" value="Gestión de reputación Online / Redes Sociales">
<label for="red">Gestión de reputación Online / Redes Sociales</label><br>
<input type="checkbox" id="seo" name="check[]" value="Gestión Estratégica (SEO, e-mail marketing)">
<label for="seo">Gestión Estratégica (SEO, e-mail marketing)</label><br><br>***
<div class="form-group">
<label for="txtMessage">Otros:</label>
<textarea placeholder="Message" class="form-control required"
id="txtMessage" name="txtMessage" rows="10"></textarea>
</div>
<div class="form-group">
<label for="txtCaptcha"></label>
<input
type="text" class="form-control required captcha"
placeholder="Are you human?" id="txtCaptcha" name="txtCaptcha" />
</div>
<div class="form-group">
<input type="button" id="btn-Send" value="Send" class="btn btn-theme-inverse" />
</div>
<div class="col-lg-12" id="contact-form-message"></div>
</form>
PHP->
<?php
$formType = $_POST["formType"];
$MailTo = 'victor.fernandez.gayan#gmail.com';
$txtName = $_POST["txtName"];
$txtEmail = $_POST["txtEmail"];
$txtRating = "";
$txtWebsite = "";
$txtMessage = $_POST["txtMessage"];
$putavariable = $_POST["check"];
if(!(empty($_POST['check']))){
foreach($_POST['check'] as $value){
$check_msg .= "Persona interesada en: $value\n";
}
}
if ($formType == "comments") {
$txtWebsite = $_POST["txtWebsite"];
}
if ($formType == "reviews") {
$txtRating = $_POST["txtRating"];
}
$success = TRUE;
try{
if(trim($txtEmail)==NULL){
throw new Exception("Please enter your e-mail id.");
}
else
{
if (!preg_match("/\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", trim($txtEmail)))
{
throw new Exception("Please enter the valid e-mail.");
}
}
if(trim($txtName)==NULL){
throw new Exception("Please enter your name.");
}
if(trim($txtMessage)==NULL){
throw new Exception("Please enter your message.");
}
if($formType == "contact") {
$MailSubject = "New Contact Mail";
$MailBody = "<strong>Email: </strong> ".$txtEmail."<br />";
$MailBody .= "<strong>Nombre: </strong> ".$txtName."<br />";
$MailBody .= "<strong>Le interessa: </strong> ".$putavariable."<br />";
$MailBody .= "<strong>Otros intereses: </strong> ".$txtMessage."<br />";
}
if($formType == "comments") {
$MailSubject = "New Comment Mail";
$MailBody = "<strong>Email: </strong> ".$txtEmail."<br />";
$MailBody .= "<strong>Name: </strong> ".$txtName."<br />";
$MailBody .= "<strong>Website: </strong> ".$txtWebsite."<br />";
$MailBody .= "<strong>Comment: </strong> ".$txtMessage."<br />";
}
if($formType == "reviews") {
$MailSubject = "New Review Mail";
$MailBody = "<strong>Email: </strong> ".$txtEmail."<br />";
$MailBody .= "<strong>Name: </strong> ".$txtName."<br />";
$MailBody .= "<strong>Rating: </strong> ".$txtRating."<br />";
$MailBody .= "<strong>Review: </strong> ".$txtMessage."<br />";
}
$MailFrom = $txtEmail;
$MailHeaders = 'MIME-Version: 1.0' . "\r\n";
$MailHeaders .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$MailHeaders .= "From: <".$txtEmail.">"."\r\n";
$result = mail($MailTo, $MailSubject, $MailBody, $MailHeaders);
if(!$result){
throw new Exception("Email no enviado:(");
}
$success = TRUE;
}
catch (Exception $e){
header("Status: 400 Bad Request", TRUE, 400);
echo($e->getMessage());
$success = FALSE;
}
if ($success)
{
header("Status: 200 OK", TRUE, 200);
// add your custom success message here
echo("EMAIL ENVIADO :)");
}
else
{
header("Status: 400 Bad Request", TRUE, 400);
}
?>
I revised my form:
<label for="txtMessage">Información:</label><br>
<input type="checkbox" id="web" name="check[]" value="Creación de web">
<label for="web">Creación de web</label><br>
<input type="checkbox" id="red" name="check[]" value="Gestión de reputación Online / Redes Sociales">
<label for="red">Gestión de reputación Online / Redes Sociales</label><br>
<input type="checkbox" id="seo" name="check[]" value="Gestión Estratégica (SEO, e-mail marketing)">
<label for="seo">Gestión Estratégica (SEO, e-mail marketing)</label><br><br>
<div class="form-group">
<label for="txtMessage">Otros:</label>
<textarea placeholder="Message" class="form-control required" id="txtMessage" name="txtMessage" rows="10"></textarea>
and PHP:
$formType = $_POST["formType"];
$MailTo = 'victor.fernandez.gayan#gmail.com';
$txtName = $_POST["txtName"];
$txtEmail = $_POST["txtEmail"];
$txtRating = "";
$txtWebsite = "";
$txtMessage = $_POST["txtMessage"];
$putavariable = $_POST["check"];
var_dump($_POST);
if(!(empty($_POST['check']))){
foreach($_POST['check'] as $value){
$check_msg .= "Persona interesada en: $value\n";
}
}
And result:
array(5) { ["formType"]=> string(7) "contact" ["txtName"]=> string(10) "Imchecking" ["txtEmail"]=> string(25) "Imchecking#Imchecking.com" ["txtMessage"]=> string(16) "hello Imchecking" ["txtMailTo"]=> string(0) "" } EMAIL SENDED :)
I thing I'm close but I dont know how to procee it. I checked the checkboxes on before sent the email but nothing happens.

Categories