JQuery + PHP contact form multiple checkbox - javascript

I have a little problem with my contact form. I added multiple checkbox but once proceeded the email only shows 1 when I check all of them.
I might be missing something.
Here is my code if anyone can help me.
Thanks
HTML
<div id="contact_form">
<div style="color:#000;" id="contact_results"></div>
<div id="contact_body">
<div class="form-group">
<input type="text" class="form-control" name="nom" id="nom" placeholder="Nom">
</div>
<div class="form-group">
<input type="text" class="form-control" name="prenom" id="prenom" placeholder="Prenom">
</div>
<div class="form-group">
<input type="text" class="form-control" name="annee" id="annee" placeholder="Année de naissance">
</div>
<div class="form-group">
<label><input type="checkbox" name="id[]" id="id1" value="Habille">Habillé</label>
<label><input type="checkbox" name="id[]" id="id2" value="Sexy">Sexy (+18)</label>
<label><input type="checkbox" name="id[]" id="id3" value="Lingerie - Maillot de bain">Lingerie/Maillot de bain (+18)</label>
<label><input type="checkbox" name="id[]" id="id4" value="Nue cache">Nue caché (+18)</label>
<label><input type="checkbox" name="id[]" id="id5" value="Nue non cache">Nue non caché (+18)</label>
</div>
<div class="form-group">
<input type="text" class="form-control" name="ville" id="ville" placeholder="ville">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<textarea class="form-control" rows="3" name="message" id="message" placeholder="Votre message"></textarea>
</div>
<button type="submit" id="submit_btn" class="btn btn-primary btn-xl page-scroll">Envoyer</button>
</div>
</div>
JQuery
$(document).ready(function() {
$("#submit_btn").click(function() {
var proceed = true;
$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
post_data = {
'user_nom' : $('input[name=nom]').val(),
'user_prenom' : $('input[name=prenom').val(),
'user_message' : $('textarea[name=message]').val(),
'user_ville' : $('input[name=ville]').val(),
'user_email' : $('input[name=email]').val(),
'user_theme' : $("input[name='id[]']:checked").val(),
'user_annee' : $('input[name=annee]').val(),
};
$.post('modelc.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").val('');
$("#contact_form #contact_body").slideUp(); //hide form after success
}
$("#contact_form #contact_results").hide().html(output).slideDown();
}, 'json');
}
});
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
PHP
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$headers = 'From: '.$user_email.'' . "\r\n";
$headers .= 'Reply-To: '.$user_email.'' . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if($_POST)
{
$to_email = "hello#originsphotography.eu"; //Recipient email, Replace with own email here
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'Erreur',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_nom = filter_var($_POST["user_nom"], FILTER_SANITIZE_STRING);
$user_prenom = filter_var($_POST["user_prenom"], FILTER_SANITIZE_STRING);
$user_message = filter_var($_POST["user_message"], FILTER_SANITIZE_STRING);
$user_ville = filter_var($_POST["user_ville"], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$user_annee = filter_var($_POST["user_annee"], FILTER_SANITIZE_EMAIL);
$user_theme = $_POST["user_theme"];
$subject = "Contact site internet";
$from = "www.originsphotography.eu";
//additional php validation
if(strlen($user_nom)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Le champ est trop court ou vide'));
die($output);
}
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Veuillez entrer une adresse email valide'));
die($output);
}
//email body
$message_body = "Nom : ".$user_nom."\r\n\r\nPrénom : ".$user_prenom."\r\n\r\nEmail : ".$user_email."\r\n\r\nMessage : ".$user_message."\r\n\r\nVille : ".$user_ville."\r\n\r\nTheme : ".$user_theme."\r\n\r\nAnnee : ".$user_annee ;
//proceed with PHP email.
$headers = 'From: '.$user_email.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Merci, '.$user_prenom .' pour votre message. Je vous réponds très vite !'));
die($output);
}
}
?>

No need to use .val() and [] in name to get values of checkboxes in jquery
$("input[name='id']:checked");
to get selected values you can serialize them
console.log($('input[name='id']:checked').serialize());
or you can use each loop
$('input[name='id']:checked').each(function() {
console.log(this.value);
});
or if you want to paas them through ajax
just add it in variable like
var checked = $('input[name='id']:checked').serialize();
or if you want to push it's values in array
var checkboxValues = [];
$('input[name=id]:checked').map(function() {
checkboxValues.push($(this).val());
});

Related

Data from new HTML form input field not being passed to email using PHP and JavaScript

This is my first post on the site. I added a new input field to a previously working HTML contact form in order to collect the user’s street address. Although all other input fields continue to pass data to the email generated after the form is submitted, data is not being passed to the email with the street address. I have copied below the associated HTML, PHP, and JavaScript files, as well as an example of what data is now sent to the email.
I truly appreciate any help with what I am doing wrong. I have spent over 8 hours trying to solve this problem, but so far have been unsuccessful. Thank you!
Here is an example of the data now being placed into the email generated. Notice that the only data NOT being passed is the text that was input into the street address field of the contact form (blank).
Name: Tim Spyridon
Address:
Phone Number: 513-662-1464
Message:
Made major changes to PHP script. This may work!
Here is the HTML code used for the contact form:
<!-- Form Starts -->
<div id="contact_form">
<div class="form-group">
<label>Name <span class="required">*</span></label>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required>
<label>Street Address and City <span class="required">*</span></label>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required>
<label>Email Address <span class="required">*</span></label>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required>
<label>Phone Number including Area Code <span class="required">*</span></label>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required>
<label>Message <span class="required">*</span></label>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required></textarea>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
Here is my JavaScript code from a file called contact.js:
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('php/sendmail.php', post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
//reset values in all input fields
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
Here is my PHP script from a file called sendmail.php:
<?php
if($_POST)
{
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die($output);
}
}
?>
In support of the comment made last night (above ) here is the test version of the above script which appears to work perfectly well in terms of the newly added message field. There are comments at places where things were changed - some semantic, others functional.
<?php
if( $_POST ){
# Simple Boolean to switch between live & test mode
# whilst testing that this script does or does not
# function correctly.
$b_live=false;
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) AND strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) != 'xmlhttprequest' ) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
# If the script is live, attempt to send the emails
if( $b_live ){
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
}else{
# emulate either a success or failure randomly
# to aid testing of ajax callback
$send_mail=mt_rand(0,1);
# you can verify the message is being populated
$_POST['MESSAGE']=$message;
$_POST['TIME']=date( DATE_ATOM );
file_put_contents( __DIR__ . '/ajax.log', json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
}
if(!$send_mail){
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die( $output );
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die( $output );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Contact</title>
</head>
<body>
<!--
The `label` attribute **must** be associated with whichever form element
it is supposed to reference. This can be done either by including the
`for` attribute in the label with the input element's ID OR the form element
must be within the label itself - as shown below.
-->
<div id="contact_form">
<div class="form-group">
<label>
Name <span class="required">*</span>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required />
</label>
<label>
Street Address and City <span class="required">*</span>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required />
</label>
<label>
Email Address <span class="required">*</span>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required />
</label>
<label>
Phone Number including Area Code <span class="required">*</span>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required />
</label>
<label>
Message <span class="required">*</span>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required /></textarea>
</label>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
<!--
Added this DIV to allow output to be rendered
-->
<div id='contact_results'></div>
<script>
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
/*
*****************************************************
This is the ONLY change made in the Javascript
*****************************************************
*/
const _URL=location.href; // 'php/sendmail.php'
$.post( _URL, post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
</script>
</body>
</html>
With this I could not replicate the issues stated in the question: The $message variable is populated and can be inspected in the console or the ajax.log file that is generated in test mode.

Stop contact form from replying in new tab. My OCD is fistfighting my ADD over contact form

this is my html, my php, and ajax for a contact form. It works great except it post the relpys in a new browser tab. I have spent hours trying to correct it. Please help.
html-
<!-- form fields -->
<form action="assets/php/contact.php" method="post" name="contactform" id="contactform" class=" animated out" data-animation="fadeInUp" data-delay="0">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Name">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="subject" id="subject" placeholder="Subject">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" name="message" id="message" placeholder="Message..."></textarea>
</div>
</div>
</div>
</fieldset>
<!-- submit button -->
<div class="form-group">
<input type="submit" name="submit" value="Send message" id="submit" class="btn btn-sm btn-primary">
</div>
<div id="alert"></div>
</form>
PHP-
if(!$_POST) exit;
// Email address verification, do not edit.
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'];
$email = $_POST['email'];
$message = $_POST['message'];
if(trim($name) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You must enter your name.</p></div>';
exit();
} else if(trim($email) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter a valid email address.</p></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You have entered an invalid e-mail address, try again.</p></div>';
exit();
}
if(trim($message) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter your message.</p></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$message = stripslashes($message);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "your#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name ." . PHP_EOL . PHP_EOL;
$e_content = "\"$message\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<div class='notification success clearfix'><p>Thank you <strong>$name</strong>, your message has been submitted to us.</p></div>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
JS-
/* ==============================================
Contact Form
=============================================== */
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#alert").slideUp(750,function() {
$('#alert').hide();
$('#submit')
.after('<img src="assets/images/ajax-loader.GIF" class="contactloader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
},
function(data){
document.getElementById('alert').innerHTML = data;
$('#alert').slideDown('slow');
$('#contactform img.contactloader').fadeOut('slow',function(){$(this).remove();});
$('#submit').removeAttr('disabled');
if(data.match('success') !== null) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
}
);
});
return false;
});
I want error or success messages to show on the contact.html page and not open a new browser tab.
Thank you advance for help restore my sanity.
Cheers
You just need to prevent the default form submit from firing, which will post the content to the URL in your form action.
$('#contactform').submit(function(event){
event.preventDefault();
...
});

Tag in form does not work

I developed a contact form on my website but in this form it has a select unde the person will be able to choose a service but I have no idea how to insert this in my code I would like to know if it is possible. At the beginning my code works I just can not capture The services option. Follow my codes and error image on the console
Realize that in the image the only field that does not appear anything and that of the service
HTMl:
<form id="form-elements" onSubmit="return false">
<div class="row">
<div class="col-md-12 center">
<div id="result"></div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control input-border" placeholder="Nome" name="name"
id="name" required></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<input type="email" class="form-control input-border" placeholder="E-mail" name="email"
id="email" required></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control input-border" placeholder="Telefone" name="phone"
id="phone" required>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<select class="form-control input-border" name="service" id="service" required>
<option disabled selected>Escolha um serviço</option>
<option value="comediante">Comediante</option>
<option value="apresentador">Apresentador</option>
<option value="ator">Ator</option>
<option value="reporter">Repórter</option>
<option value="cerimonialista">Cerimonialista</option>
<option value="roteirista">Roteirista</option>
</select>
</div>
</div>
<div class="col-xs-12">
<textarea id="input" class="form-control message-input" rows="7" required="required"
placeholder="Mensagem" name="message" id="message"></textarea>
</div>
<button type="submit" class="btn btn-default buttons button-send" id="submit_btn">Quero Contratar</button>
</div>
</form>
JS:
//Contact Us
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_telephone = $('input[name=phone]').val();
var user_service = $('input[name=service] option:selected').val();;
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
var post_data, output;
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_message=="") {
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userTelephone':user_telephone, 'userService':user_service, 'userMessage':user_message};
//Ajax post data to server
$.post('contact.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
}else{
output = '<div class="alert-success" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
//reset values in all input fields
$('#form-elements input').val('');
$('#form-elements textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#form-elements input, #form-elements textarea").keyup(function() {
$("#result").slideUp();
});
PHP:
<?php
if($_POST)
{
$to_Email = "felipe#agenciafront.com.br"; //Replace with recipient email address
$subject = 'Contato para contratação de serviços'; //Subject line for emails
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Os campos de entrada estão vazios! '));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = $_POST["userTelephone"];
$user_Service = filter_var($_POST["userService"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'O campo nome não pode ficar vazio'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Por favor ultilize um e-mail válido'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Por favor insira uma mensagem'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
$message_Body .= "<strong>Serviço: </strong>". $user_Service ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion(). "\r\n" .
'Content-type: text/html;charset=UTF-8';
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Ocorreu um erro tente novamente'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Olá '. $user_Name .' Obrigado pelo seu contato retornaremos em breve.'));
die($output);
}
}
?>
$('input[name=service]').val();
Service is not an input, its a select. change to
$('select[name="service"]').val()
select element doesn't have value, that's why you have to get value of selected option. So you get that value like this:
Edit
As Todilo noticed, you are trying to get element with input tag, while select element isn't input.
$('select[name="service"] option:selected').val();
Example
console.log($('select option:selected').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select>
<option>Option 1</option>
<option selected>Option 2</option>
</select>

Ajax php contact form no email

Cannot seem to get this code to work it's says it sending the email but somewhere on the line it's get stuck. have not access to the logs at this moment from the host, so can't check and this should send the emails from my point of view atht this moment
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'The input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = $_POST["userTelephone"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name field can not be empty'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please use a valid email address'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a message'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion() . "\r\n" .
'Content-type: text/html';
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'An error has occurred, please try again'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hello '.$user_Name .'Thanks for your contact we will return soon.'));
die($output);
}
}
here is the JS
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_telephone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
var post_data, output;
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_message=="") {
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userTelephone':user_telephone, 'userMessage':user_message};
//Ajax post data to server
$.post('contact.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
}else{
output = '<div class="alert-success" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
//reset values in all input fields
$('#form-elements input').val('');
$('#form-elements textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#form-elements input, #form-elements textarea").keyup(function() {
$("#result").slideUp();
});
html
<form id="form-elements" onSubmit="return false">
<div class="row">
<div class="col-md-12 center"><div id="result"> </div> </div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="Namn" name="name" id="name" required></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<input type="email" class="form-control" placeholder="Email Adress" name="email" id="email" required></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="Telefon nummer" name="phone" id="phone" required>
</div>
</div>
<div class="col-xs-12">
<textarea id="input" class="form-control" rows="7" required="required" placeholder="Meddelande" name="message" id="message" ></textarea>
</div>
<button type="submit" class="btn btn-default buttons" id="submit_btn">Skicka</button>
</div>
</form>
Dunno but some othere said i should insert
$("#submit_btn").click(function() {
e.preventDefault();
is the problem that I using ?
onSubmit="return false"

Load a file, send it by email and stay on the same page

I have this code which actually is not working completely, I get the email with all the info, but the email does not include the file that I'm trying to attach... (the only way I get it is deleting the jquery ajax function) Any idea why? (I did this because I want to get an alert in the same page after submit the form) Thanks for your help!
HTML
<form class="ajax_nueva_idea" action="php/send_idea.php" method="post" enctype="multipart/form-data">
<div>
<input required="" id="nombreproyecto" name="nombreproyecto" type="text" class="validate">
</div>
<div>
<input required="" id="sector_for" name="sector_for" type="text" class="validate">
</div>
<div>
<input required="" id="ubigeo_for" type="text" name="ubigeo_for" class="validate">
</div>
<div>
<input required="" id="videoex_for" name="videoex_for" type="text" class="validate">
</div>
<div>
<select required="" id="etapa_for" name="etapa_for">
<option value="0"</option>
<option value="1">1/4</option>
<option value="2">2/4</option>
<option value="3">3/4</option>
<option value="4">4/4</option>
</select>
</div>
<div>
<input name="attachment" type="file">
</div>
<div>
<textarea required="" id="info_for" name="info_for"></textarea>
</div>
<div>
<button type="submit" name="action" id="enviar_proyecto">Guardar
</button>
</div>
</form>
PHP
<?php
$to = 'example#msn.com';
$nombreproyecto = $_POST['nombreproyecto'];
$sector = $_POST['sector_for'];
$ciudad = $_POST['ubigeo_for'];
$video = $_POST['videoex_for'];
$etapa = $_POST['etapa_for'];
$subject = "'gobig.com.co' Nuevo proyecto "."'".$nombreproyecto."'";
$message =
"Cargo: ".$nombreproyecto."\n".
"Sector o industria: ". $sector ."\n".
"Ciudad: ".$ciudad ."\n".
"Link video:". $video ."\n".
"Etapa del proyecto:".$etapa."\n" .
"Frase convencer: ".$_POST['info_for'];
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
$headers = "From: $nombreproyecto";
if (file($tmpName)) {
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
//echo "A email has been sent to: $to";
}
else{
//echo "Error in Email sending";
}
?>
JAVASCRIPT
jQuery('.ajax_nueva_idea').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
alert('Idea guardada exitosamente!');
$('#enviar_proyecto').html('Guardado <i class="material-icons right">check</i>');
},
error : function(){
alert('Something wrong');
}
});
return false;
});
You cannot upload files that easily using AJAX by simply using serialize on form. You'll need new FormData object, which is already explained here: How to use FormData for ajax file upload

Categories

Resources