Error on contact form - php

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");
});

Related

Refresh page after submit contact form [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 2 years ago.
Hello guys i already have a problem with my contact form example when i press send email, email is going but the page wont do anything or even it doesnt show succes message, i want the contact form to be cleared after i press submit button.. website
My html code
<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12">
<div class="contact-form mb50 wow fadeIn">
<h2>Send Message</h2>
<form action="process.php" id="contact-form" method="post">
<div class="form-group" id="name-field">
<div class="form-input">
<input type="text" class="form-control" id="form-name" name="form-name" placeholder="Name.." required>
</div>
</div>
<div class="form-group" id="email-field">
<div class="form-input">
<input type="email" class="form-control" id="form-email" name="form-email" placeholder="Email.." required>
</div>
</div>
<div class="form-group" id="phone-field">
<div class="form-input">
<input type="text" class="form-control" id="form-phone" name="form-phone" placeholder="Phone...">
</div>
</div>
<div class="form-group" id="message-field">
<div class="form-input">
<textarea class="form-control" rows="6" id="form-message" name="form-message" placeholder="Your Message Here..." required></textarea>
</div>
</div>
<div class="form-group">
<button type="submit">Send Message</button>
</div>
My process.php code
<?php
// Configure your Subject Prefix and Recipient here
$subjectPrefix = '[Contact Form Website]';
$emailTo = '<info#mywebsite.com>';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['name']));
$email = stripslashes(trim($_POST['email']));
$phone = stripslashes(trim($_POST['phone']));
$message = stripslashes(trim($_POST['message']));
if (empty($name)) {
$errors['name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email is invalid.';
}
if (empty($phone)) {
$errors['phone'] = 'Phone is required.';
}
if (empty($message)) {
$errors['message'] = 'Message is required.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "$subjectPrefix $subject";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Phone: </strong>'.$phone.'<br />
<strong>Message: </strong>'.nl2br($message).'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . "<$email>" . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
$data['success'] = true;
$data['message'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
My contact-form.js code
(function ($, window, document, undefined) {
'use strict';
var $form = $('#contact-form');
$form.submit(function (e) {
// remove the error class
$('.form-group').removeClass('has-error');
$('.help-block').remove();
// get the form data
var formData = {
'name' : $('input[name="form-name"]').val(),
'email' : $('input[name="form-email"]').val(),
'phone' : $('input[name="form-phone"]').val(),
'message' : $('textarea[name="form-message"]').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('has-error');
$('#name-field').find('.form-input').append('<span class="help-block">' + data.errors.name + '</span>');
}
if (data.errors.email) {
$('#email-field').addClass('has-error');
$('#email-field').find('.form-input').append('<span class="help-block">' + data.errors.email + '</span>');
}
if (data.errors.phone) {
$('#phone-field').addClass('has-error');
$('#phone-field').find('.form-input').append('<span class="help-block">' + data.errors.phone + '</span>');
}
if (data.errors.message) {
$('#message-field').addClass('has-error');
$('#message-field').find('.form-input').append('<span class="help-block">' + data.errors.message + '</span>');
}
} else {
// display success message
$form.html('<div class="alert alert-success">' + data.message + '</div>');
}
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
Cant you simply add location.reload() in your Js at the end of your function when sending succeeds?
try to add a function in js like that
function myFunction() {
location.replace("https://URL")
}
And then onclick="myFunction()"

form with attachment - jquery ajax php

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;
}
}

PHP contact form redirects to contact.php with success message

I downloaded some files from Bootstrapious to make a php form work. I have it send it e-mails, but no matter what I do it redirects to the php file which comes out as a blank page with the success message (no format, tho).
HTML
<form id="contact-form" method="post" action="../prueba/assets/php/contact.php">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<label for="name">Nombre</label>
<input id="name" type="text" name="name" class="form-control" placeholder="Escribe tu nombre" required data-error="Por favor, escribe tu nombre.">
<label for="email">Email</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Escribe tu e-mail" required data-error="Por favor, escribe tu e-mail.">
<label for="comment">Mensaje</label>
<textarea id="comment" name="comment" class="form-control" rows="3" required data-error="Por favor, escribe tu mensaje."></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-default">Enviar <span class="glyphicon glyphicon-send"></button>
</div>
PHP
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
// configure
$from = 'Con Ilan a la India <conilanalaindia#gmail.com>';
$sendTo = 'andreaisyourfriend#gmail.com';
$subject = 'Nuevo mensaje del formulario';
$fields = array();
$fields["name"] = "Nombre";
$fields["email"] = "E-mail";
$fields["comment"] = "Message"; // array variable name => Text to appear in the email
$okMessage = 'El formulario ha sido enviado correctamente. Te contactaremos dentro de poco.';
$errorMessage = 'Ha ocurrido un error al enviar el formulario. Por favor, inténtalo nuevamente.';
// let's do the sending
try
{
$emailText = "Hay un nuevo mensaje de la web Con Ilan a la India";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
$headers = array('Content-Type: text/html; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
JS
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "../prueba/assets/php/contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Solved it. I wasn't calling the validator.js nor the contact.js correctly in the index.html body. Duh. Sorry to bother!

Why is php's mail() function successfully sending mail but with blank fields?

Email is arriving at the destination address but with blank fields. What is the cause?
My use of mail() is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'info#siteaddress.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
And the form HTML is:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" class="form-control" required placeholder="Name" name="name" id="name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="text" class="form-control" required placeholder="Email address" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message" name="message" id="message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</div>
</div>
</form>
$subject = #trim(stripslashes($_POST['subject'])); but your form don't have subject, you should add it.
Don't suppress errors by #, because you never will know what exactly happens with your code.
Finally Got the Answer.... Problem is that my form was not posting anything because the following script was missing
<script>
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'),$(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
</script>
i have added $(this).serialize() to the script and now the mail is working properly...
Thanks all of you....
Hi I´m have the same problem on a 000webhost app. I solve this with two moodifications
1rst:
Add var name = $("input#name").val(); for a form values and in to the ajax function name: name, for a form values
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: {
name: name,
email: email,
subject: subject,
message: message,
},
cache: false,
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email enviandose</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success"> Gracias por la consulta, a la brevedad estaremos respondiendo</p>').delay(3000).fadeOut();
//clear all fields
$('#main-contact-form').trigger("reset");
});
});
2nd: The tag id"name" id"email" id"XX" in mi Form in my case
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
//to Replace This
$header .= 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>',,$header);
if( $success == true )
{
//success Message
}
else{
//Error Message
}

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!

Categories