I'm trying to put my email form to work, but something is wrong.
I'm having no problems receving the email, but the process of ajax script with JSON (validation successful) isn't working properly and i don't know why.
My HTML:
<form id="feedback" method="post" action="">
<div class="enter-data">
<label for="name"><span>Nome:</span></label>
<input name="name" id="name" type="text" class="formbox">
</div>
<div class="enter-data">
<label for="email"><span>E-mail:</span> </label>
<input name="email" id="email" type="text" class="formbox">
</div>
<div class="enter-data">
<label for="telefone"><span>Telefone:</span></label>
<input name="telefone" id="telefone" type="text" class="formbox">
</div>
<div class="enter-commnet">
<label for="comments"></label>
<textarea name="comments" id="comments"></textarea>
</div>
<div class="button_comment-bx">
<button class="button_comment last" name="send" id="send" type="submit">Enviar</button>
<button class="button_comment" name="reset" id="reset" type="reset">Limpar</button>
</div>
</form>
My jquery **
(EDITED)
**:
$(document).ready(function(){
$("#feedback").submit(function(){
$(".error").remove();
var check = true;
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var name = $("#name").val();
var email = $("#email").val();
var telefone = $("#telefone").val();
// Validate Name
if (name == '') {
check = false;
$('#name').after('<div class="error">* Preencha o seu nome!</div>');
}
else if (name.length < 3) {
check = false;
$('#name').after('<div class="error">* Nome demasiado curto!!</div>');
}
// Validate E-mail
if (email == '') {
check = false;
$('#email').after('<div class="error">* Preencha o seu email!</div>');
}
else if (email.length < 5) {
check = false;
$('#email').after('<div class="error">* Email demasiado curto!</div>');
}
else if(!emailPattern.test(email)){
check = false;
$('#email').after('<div class="error">* E-mail não é válido!</div>');
}
// Validate Telefone
if (telefone == '') {
check = false;
$('#telefone').after('<div class="error">* Preencha o seu telefone!</div>');
}
else if (telefone.length < 5) {
check = false;
$('#telefone').after('<div class="error">* Telefone não é válido!</div>');
}
// If validation is successful
$.ajax({
type: "POST",
url: "contact3.php",
data: $("#feedback").serialize(),
dataType: "json",
success: function(response){
$("#comments").after('<div class="success">Email enviado com sucesso!</div>');
$('#name').val('');
$('#email').val('');
$('#telefone').val('');
$('#comments').val('');
}
});
});
});
My PHP script for sending mail **
(EDITED)
**
<?php
$to ='myemail#email.com';
// Contact subject
$subject ="Contacto Site";
$header="from: $name <$email>";
$nome = $_POST['name'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$mensagem = $_POST['comments'];
// Corpo da mensagem
$body = "Nome: ".$nome;
$body.= "\n";
$body.= "Email: ".$email;
$body.= "\n";
$body.= "Telefone: ".$telefone;
$body.= "\n";
$body.= "\n";
$body.= nl2br($mensagem);
// Enter your email address
mail($to,$subject,$body,$header);
echo json_encode(array('mailSuccess' => 1));
help me please!
You are missing return value of your script. You have to echo json_encoded string, which jquery will check in if (!response.mailSuccess)
<?php
$to ='myemail#email.com'; // Contact subject $subject ="Contacto Site";
$header="from: $name <$email>";
$nome = $_POST['name']; $email = $_POST['email']; $telefone = $_POST['telefone']; $mensagem = $_POST['comments'];
// Corpo da mensagem $body = "Nome: ".$nome; $body.= "\n"; $body.= "Email: ".$email; $body.= "\n"; $body.= "Telefone: ".$telefone; $body.= "\n"; $body.= "\n"; $body.= nl2br($mensagem);
// Enter your email address
mail($to,$subject,$body,$header);
echo json_encode(array('mailSuccess' => 1));
?>
EDITED:
$.ajax({
type: "POST",
url: "contact3.php",
data: $("#feedback").serialize(),
dataType: "json",
success: function(response){
$("#comments").after('<div class="success">Email enviado com sucesso!</div>');
$('#name').val('');
$('#email').val('');
$('#telefone').val('');
$('#comments').val('');
}
});
Related
Hello I would like to attach a file and send it using jQuery AJAX and PHP, right now it just send the text, can some body help me about what it follows to attach the file and send the email with it,
Then i will proceed with validations,
I will show the complete solution after achieve it
This is the form
<form class="parte-form" enctype="multipart/form-data">
<input type="text" class="txt-field txt-full pName" name="pName" placeholder="* Nombre" required="required">
<div class="half-input-cont">
<input type="text" class="txt-field txt-half" name="pPhone" placeholder="Telefono">
<input type="text" class="txt-field txt-half" name="pEmail" placeholder="* Correo" required="required">
</div>
<textarea class="txt-field txt-full txt-area" placeholder="Mensaje" name="pMsg"></textarea>
<div class="input-cont">
<label class="txt-file" for="cv">Adjuntar C.V.<p>Seleccionar archivo</p> <span>No se ha elegido archivo</span></label>
<input type="file" class="txt-file-btn" id="cv" name="pFile">
</div>
<div class="more-btn-cont form-btn-cont">
<input type="hidden" name="frm-action" value="par-form">
<input type="submit" class="btn btn-blue-l btn-par" name="pPar" value="Enviar solicitud">
</div>
</form>
this is the data preparation to be send - jQuery Ajax
$(data);
function data(){
$('.btn-par').click(parte);
}
function parte(e){
e.preventDefault();
var data = $('.parte-form').serializeArray();
$.ajax({
type: "POST",
url: "data/comp-actions.php",
data: data,
beforeSend: function(){
},
success: function (response) {
if (response == 1) {
var name = $('.pName').val();
$('.popup-name').html(name)
$('.popup-send').removeClass('hidden');
$('.popup-close').click(function(){
$('.popup-send').addClass('hidden');
});
} else {
console.log('Error al enviar');
}
}
});
}
This is the data recollection and sender - PHP
//Cotizar values
$pName = $_POST['pName'];
$pPhone = $_POST['pPhone'];
$pEmail = $_POST['pEmail'];
$pMsg = $_POST['pMsg'];
$pPar = $_POST['pPar'];
//File name
$fileName = $_FILES['pFile']['name'];
$fileTmp = $_FILES['pFile']['tmp_name'];
$filePath = "files/".$fileName;
//File metadata
$fileType = $_FILES['pFile']['type'];
$fileSize = $_FILES['pFile']['size'];
// $fileError = $_FILES['pFile']['error'];
//Send mail
if($pName != "" && $pEmail != ""){
$to = "my#email.com";
$subject = "$pName Desea unirse al equipo";
$headers = "From: $pEmail";
$info = "$pName, se comunica con nosotros para unirse al equipo\n"
. "\n"
. "\n"
. "Datos del solicitante\n"
. "Nombre: $pName\n"
. "Telefono: $pPhone\n"
. "Email: $pEmail\n"
. "mensaje: $pMsg\n"
. "\n"
. "\n"
. "Datos del archivo\n"
. "Archivo: $fileName\n"
. "Tipo de archivo: $fileType\n"
. "Tamaño del archivo: $fileSize\n"
. "Ruta del archivo: $filePath\n"
. "\n"
. "\n"
. "\n";
if (mail($to, $subject, $info, $headers)) {
echo 1;
}else{
echo 0;
}
}
Use FormData to grab file contents as well
var form = $(".parte-form")[0];
var data = new FormData(form);
In your ajax call, set
processData: false
Here is my solution for this feature
This solution could be improved I'm working on it if you have a better solution, please pot it or post the link to the solution
File with the form, the call to your css and js files, in case of not need it you can remove the recaptcha div
<form class="parte-form" id="contact_body" method="POST" action="send-unete.php" enctype="multipart/form-data">
<input type="text" class="txt-field txt-full pName txt-text" name="pName" placeholder="* Nombre" required="required">
<div class="half-input-cont">
<input type="tel" class="txt-field txt-half txt-phone" name="pPhone" placeholder="Teléfono">
<input type="email" class="txt-field txt-half" name="pEmail" placeholder="* Correo" required="required">
</div>
<textarea class="txt-field txt-full txt-area" placeholder="Mensaje" name="pMsg"></textarea>
<div class="input-cont">
<!-- it changes the style of the input type file -->
<label class="txt-file" for="cv">Adjuntar C.V.<p>Seleccionar archivo</p> <span>No se ha elegido archivo</span></label>
<input type="file" class="txt-file-btn" id="cv" name="pFile[]">
</div>
<div class="g-recaptcha" data-sitekey="your key"></div>
<div class="more-btn-cont form-btn-cont">
<!-- Set of email where the email will be send -->
<input type="hidden" name="pEmailSet" value="<?php the_field( 'email_set_unete', 216) ?>">
<!-- Identifies the form in case of have more forms or actions like save, delete, load etc -->
<input type="hidden" name="frm-action" value="par-form">
<input type="submit" class="btn btn-blue-l btn-par" name="pPar" value="Enviar solicitud">
</div>
</form>
<!-- Success popup -->
<div class="popup-send layer hidden">
<div class="wrapper">
<div class="popup-info">
<div class="popup-title">
<p>Mensaje enviado</p>
<button class="popup-close">X</button>
</div>
<p class="popup-msg"><b class="popup-bold popup-name"></b>, Tus datos han sido enviados al área correspondiente en la brevedad nos comunicaremos contigo, para darle seguimiento a tu petición, <b class="popup-bold">Gracias</b></p>
</div>
</div>
</div>
<!-- Error popup -->
<div class="popup-error layer hidden">
<div class="wrapper">
<div class="popup-info">
<div class="popup-title">
<p>Mensaje no enviado</p>
<button class="popup-close">X</button>
</div>
<p class="popup-msg"></p>
</div>
</div>
</div>
<!-- it gets the mail path of the site used for references -->
<p class="dir hidden"><?php bloginfo('template_directory'); ?></p>
JS file with ajax call it recolects the data and prepar it for be reciebed by the php file
function data(){
// Action function
// $('.btn-cot').click(cotizar);
$('.btn-par').click(parte);
}
function parte(e){
$("#contact_body").submit(function(e){
e.preventDefault(); //prevent default action
proceed = true;
//if everything's ok, continue with Ajax form submit
if(proceed){
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
$.ajax({ //ajax form submit
url : "data/comp-actions.php",
type: request_method,
data : form_data,
dataType : "json",
contentType: false,
cache: false,
processData:false
}).done(function(res){ //fetch server "json" messages when done
if(res == 1){
var name = $('.pName').val();
$('.popup-name').html(name)
$('.popup-send').removeClass('hidden');
$('.popup-close').click(function(){
$('.popup-send').addClass('hidden');
});
}else{
$(".popup-error").removeClass("hidden"),
$(".popup-error .popup-msg").html('Tu mensaje no pudo ser enviado, te pedimos revises que hayas completado los <b class="popup-bold">campos requeridos (*)</b>, revisado que el archivo adjunto sea en <b class="popup-bold">formato pdf</b>, asi como marcado la <b class="popup-bold">casilla de verificación</b> y vuelvas a intentarlo, <b class="popup-bold">Gracias</b>'),
$(".popup-close").click(function() {
$(".popup-error").addClass("hidden");
})
}
});
}
});
}
This is the comp-actions.php file, it checks the submited action and loads the needed file, the recaptchalib.php must be added in order to get the recaptcha response
include('recaptchalib.php');
//Action selector
$action = $_POST['frm-action'];
$captchaResponse = $_POST['g-recaptcha-response'];
if ($captchaResponse != "") {
$captcha = 1;
if($action == "cot-form" && $captcha == 1){
include('send-cotizar.php');
} elseif($action == "par-form" && $captcha == 1){
include('send-unete.php'); //**
}elseif($captcha != 1){
echo 0;
}
} else {
echo 0;
}
This is the send-unete.php file wich is loaded after the action check and prepare the data and attachment to be send it
$pEmailSet = $_POST['pEmailSet'];
$recipient_email = $pEmailSet; //recepient
$fromUser = $_POST['pEmail'];
$from_email = $fromUser; //from email using site domain.
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die('Sorry Request must be Ajax POST'); //exit script
}
if($_POST){
$sender_name = filter_var($_POST["pName"], FILTER_SANITIZE_STRING); //capture sender name
$sender_email = filter_var($_POST["pEmail"], FILTER_SANITIZE_STRING); //capture sender email
$phone_number = filter_var($_POST["pPhone"], FILTER_SANITIZE_NUMBER_INT);
$subject = "$sender_name desea unirse a nuestro equipo";
$message = filter_var($_POST["pMsg"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['pFile'];
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("sanwebe.com");
//construct a message body to be sent to recipient
$message_body = "$sender_name, se comunica con nosotros para unirse a nuestro equipo\n";
$message_body .= "\n";
$message_body .= "Datos del solicitante\n";
$message_body .= "Nombre: $sender_name\n";
$message_body .= "Email: $sender_email\n";
$message_body .= "Tel: $phone_number\n";
$message_body .= "Mensaje: $message\n";
if($file_count > 0){ //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message_body));
//attachments
for ($x = 0; $x < $file_count; $x++){
if(!empty($attachments['name'][$x])){
if($attachments['error'][$x]>0) //exit script and output error if we encounter any
{
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder" );
print json_encode( array('type'=>'error',$mymsg[$attachments['error'][$x]]) );
exit;
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
}
}else{ //send plain email otherwise
$headers = "From:".$from_email."\r\n".
"Reply-To: ".$sender_email. "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $message_body;
}
$sentMail = mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo 1;
// print json_encode(array('type'=>'done', 'text' => 'Thank you for your email'));
// exit;
}else{
echo 0;
// print json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
// exit;
}
}
I'm trying to write a contact form with PHP, Ajax and JQuery.
The error is this:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (
but I dont know what I'm doing wrong, because I copied and paste the code of some tutorial.
i´m using foundation6, php and ajax.
I think that the error is for JSON.parse but i don´t know how resolve
This is my code, you can help me? Thanks
contact.php
<form method="post" id="formulario" data-abide novalidate action="<?php echo get_stylesheet_directory_uri(); ?>/src/assets/php/enviar.php">
<div class="campo">
<label for="nombre">Nombre:
<input type="text" id="nombre" placeholeder="Nombre" name="name" required>
<span class="form-error">Error el nombre no puede ir vacio.</span>
</label>
</div>
<div class="campo">
<label for="email">Email:
<input type="text" id="email" placeholeder="Email" name="email" required pattern="email">
<span class="form-error">Error correo vacio o invalido.</span>
</label>
</div>
<div class="campo">
<label for="fecha">Mensaje:
<textarea name="mensaje" rows="6" required></textarea>
<span class="form-error">Error correo vacio o invalido.</span>
</label>
</div>
<div class="campo">
<input type="submit" name="enviar" value="Enviar" class="button explorar">
</div>
</form>
enviar.php
<?php
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
if(is_ajax()) {
$nombre = $_POST['nombre'];
$email = $_POST['email'];
$mensaje = $_POST['mensaje'];
$header = 'From: ' . $email . "\r\n";
$header .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$header .= "Mime-Version: 1.0 \r\n";
$header .= "Content-Type: text/html";
$mensajeCorreo = 'This message was sent by: ' . $nombre . "\r\n";
$mensajeCorreo .= "Email: " . $email . "\r\n";
$mensajeCorreo .= "Mensaje: " . $mensaje . "\r\n";
$para = "email";
$asunto = "Contacto de sitio web";
mail($para, $asunto, utf8_encode($mensajeCorreo), $header );
echo json_encode(array(
'mensaje' => sprintf('El mensaje se ha enviado!')
));
} else {
die("Prohibido!");
}
app.js
// Form Contact
$('#formulario')
.on("invalid.zf.abide", function(ev,elem) {
swal(
'Error!',
'El formulario se envio incompleto',
'error'
);
})
// form validation passed, form will submit if submit event not returned false
.on("formvalid.zf.abide", function(ev,frm) {
var formulario = $(this);
$.ajax({
type: formulario.attr('method'),
url: formulario.attr('action'),
data: formulario.serialize(),
success: function(data) {
var resultado = data;
var respuesta = JSON.parse(resultado);
console.log(respuesta);
swal(
respuesta.message,
'Thank You, ' + respuesta.name + ' for your reservation!',
'success'
)
}
});
})
// to prevent form from submitting upon successful validation
.on("submit", function(ev) {
ev.preventDefault();
console.log("Submit for form id "+ev.target.id+" intercepted");
});
I freeze all the fields on the form and then issue the mail when I press the submit button. There is a Turkish character problem at the output of mail.
contact.html
<div class="col-lg-6">
<div class="well">
<h3>İletişim Formu</h3>
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name">Ad Soyad</label>
<input type="text" class="form-control" id="name" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="telefon">Telefon</label>
<input type="text" class="form-control" id="telefon" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="konu">Konu</label>
<input type="text" class="form-control" id="konu" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="sektor">Sektör</label>
<select class="form-control" id="sektor" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<option value="Özel" selected="selected">Özel</option>
<option value="Projeci">Projeci</option>
<option value="Satıcı">Satıcı</option>
<option value="Uygulayıcı">Uygulayıcı</option>
<option value="Diğer">Diğer</option>
</select>
</div>
<div class="form-group">
<label for="message">Mesajınız</label>
<textarea id="message" class="form-control" rows="5" placeholder="" required data-error="Lütfen bu alanı doldurun."></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Gönder</button>
<div id="msgSubmit" class="text-center hidden"></div>
<div class="clearfix"></div>
</form>
</div>
</div>
form-script.js
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Tüm alanları doldurdunuz mu?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var telefon = $("#telefon").val();
var konu = $("#konu").val();
var sektor = $("#sektor").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&telefon=" + telefon + "&konu=" + konu + "&sektor=" + sektor + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "text-center tada animated text-success";
} else {
var msgClasses = "text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
form-process.php
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// TELEFON
if (empty($_POST["telefon"])) {
$errorMSG .= "Telefon is required ";
} else {
$telefon = $_POST["telefon"];
}
// KONU
if (empty($_POST["konu"])) {
$errorMSG .= "Konu is required ";
} else {
$konu = $_POST["konu"];
}
// SEKTOR
if (empty($_POST["sektor"])) {
$errorMSG .= "Sektor is required ";
} else {
$sektor = $_POST["sektor"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "simple#mail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Telefon: ";
$Body .= $telefon;
$Body .= "\n";
$Body .= "Konu: ";
$Body .= $konu;
$Body .= "\n";
$Body .= "Sektör: ";
$Body .= $sektor;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Mail Output
Name: Ahmet
Email: ahmetcadi#gmail.com
Telefon: 05636588110
Konu: üğ
Sektör: Özel
Message: üğiğ
Try adding charset parameter to your AJAX request, like so:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&telefon=" + telefon + "&konu=" + konu + "&sektor=" + sektor + "&message=" + message,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
Insert
<meta charset="utf-8"/>
at the top of your Head section. Example usage :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
...etc
</head>
...
Solution of the problem. Erol Keskin Thank you.
$success = mail($EmailTo, '=?utf-8?B?'.base64_encode($Subject).'?=', $Body, 'MIME-Version: 1.0' . "<br>".'Content-type: text/html; charset=utf-8' . "<br>".'From: '.$email . "\r\n");
This is output in the email so you need to set the relevant header there as well; currently you're only setting the From header.
// send email
$success = mail(
$EmailTo,
$Subject,
$Body,
"From: {$email}\r\nContent-Type: text/plain;charset=utf8"
);
See the section on Additional Headers : http://php.net/manual/en/function.mail.php
As an aside, depending on the mailserver you may need to tweak your line terminators in the header string - Postfix expects them to be in the format relevant to the OS, so \n on *nix systems. It's unlikely to break anything but...
I have been having ongoing issues with this contact form. I am now trying to get the mobile number part to work.
I have been able to get it to work with someone code from here but it loses the format that I would like to keep. Can anyone find a reason why this form is not sending the mobile number?
site: www.krjwoodcraft.com
send.php
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$message= $_POST['message'];
$mobile = $_POST['mobile'];
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
contact.js
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var mobile = $("#mobile").val();
var error = false;
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}else{
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(name.length == 0){
var error = true;
$("#error_name").fadeIn(500);
}else{
$("#error_name").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "You Got Email" + "&message=" + message + "&mobile=" + mobile,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
html:
<!-- Contact Form -->
<div class="row">
<div class="span12">
<div class="trac_contactform">
<form id="contact_form" class="row" name="form1" method="post" action="send.php">
<div class="span6">
<input type="text" class="full" name="name" id="name" placeholder="Name" />
<div id="error_name" class="error">Please check your name</div>
</div>
<div class="span6">
<input type="text" class="full" name="email" id="email" placeholder="Email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span6">
<input type="text" class="full" name="mobile" id="mobile" placeholder="Phone Number"/>
</div>
<div class="span6">
<input type="text" class="full" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="span12">
<textarea cols="10" rows="10" name="message" id="message" class="full" placeholder="Message"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send Now" class="btn btn-large btn-primary btn-embossed" /></p>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!--END CONTACT PAGE-->
As Hanky 웃 Panky correctly pointed out you are not including the phone number to your email message. Try the following code. I stored the $_POST['message'] in a new variable called $sent_message and modified your $message variable to include the $subject, $sent_message and the $mobile variables.
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$sent_message = $_POST['message'];
$mobile = $_POST['mobile'];
$message = "Subject: " . $subject . "\r\n" . "Message: " . $sent_message . "\r\n" . "Phone number: " . $mobile;
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
You did not include it in your mail body. you have passed mobile number in php file. You got the file but you don't use it in your mail body.
include mobile number :
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message."\r\n" . "Phone number: " . $mobile), $header);
Here is the mail handler only part being received in sent emails is the actual message missing parts are name and phone.
<?php
session_start();
$email_to = "test#test.com";
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo "success";
}
else{
echo "failed";
}
?>
Here is the html part which I have checked over and over and cant figure out whats wrong
<form id="contact" class="row" name="form1" method="post" action="">
<div class="span2">
<label>Name <span class="req">*</span></label>
<input type="text" class="full" name="name" id="name"/>
<div id="error_name" class="error">Please check your name</div>
</div>
<div class="span2">
<label>Phone <span class="req">*</span></label>
<input type="text" class="full" name="phone" id="phone"/>
<div id="error_phone" class="error">Please check your phone</div>
</div>
<div class="span4">
<label>Email <span class="req">*</span></label>
<input type="text" class="full" name="email" id="email"/>
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span8">
<label>Message <span class="req">*</span></label>
<textarea cols="8" rows="10" name="message" id="message" class="full"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success"> Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit"><input type="submit" id="send" value="Send" class="btn btn-large"/></p>
</div>
</form>
Js script -------------------
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var phone = $("#phone").val();
var email = $("#email").val();
var message = $("#message").val();
var error = false;
if (name.length == 0) {
var error = true;
$("#error_name").fadeIn(500);
}
else {
$("#error_name").fadeOut(500);
}
if (phone.length == 0) {
var error = true;
$("#error_phone").fadeIn(500);
}
else {
$("#error_phone").fadeOut(500);
}
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}
else {
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "Website Enquiry" + "&message=" + message,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
Obviously, you are missing parts!... You simply declare variables, but you didn't include them in the mail itself.
In this example, I'm adding $name and $phone to $message body.
<?php
session_start();
$email_to = "test#test.com";
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'] . "\n";
$message .= "Name: " . $name . "\n";
$message .= "Phone: " . $phone;
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo "success";
}
else{
echo "failed";
}
?>