form with attachment - jquery ajax php - 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;
}
}

Related

unable to see status message after sending an email from contact page in html using php

I am trying to send an email from a contact page. the functionality is working fine, I am able to send mails from the html page but the only issue that I am facing is I am unable to see the Status div(success or failed).
Initially the page was redirecting to php file without any status message. I have added page redirect to the actual mailsend.html using header() in php. Now I want to have a status after the send operation whether mail has sent or not.
Below is the code snippet. Please help. Thanks in advance.
mailSend.html code:
<?php if(!empty($statusMsg)){ ?>
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
<form action="example.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="name" class="form-control" value="" placeholder="Name" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="email" name="email" class="form-control" value="" placeholder="Email address" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="subject" class="form-control" value="" placeholder="Subject" required="">
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Write your message here" required="" style = 'border :0.5px solid '></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" class="form-control" style = 'border :0.5px solid; height: auto;'>
</div>
<div class="submit">
<input type="submit" name="submit" class="btn" value="SUBMIT" style= 'float : right;'>
</div>
</form>
example.php code:
<?php
//first we leave this input field blank
$recipient = "";
//if user click the send button
if(isset($_POST['submit'])){
//access user entered data
$recipient = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$sender = "From: xyz#gmail.com";
//if user leave empty field among one of them
if(empty($recipient) || empty($subject) || empty($message)){
?>
<!-- display an alert message if one of them field is empty -->
<div class="alert alert-danger text-center">
<?php echo "All inputs are required!" ?>
</div>
<?php
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'abc#gmail.com';
// Sender
$from = 'xyz#gmail.com';
$fromName = 'example';
// Subject
$emailSubject = 'Contact Request Submitted by '.$recipient;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$recipient.'</p>
<p><b>Email:</b> '.$sender.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $recipient;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
?>
<!-- display a success message if once mail sent sucessfully -->
<div class="alert alert-success text-center">
<!--<?php echo "Your mail successfully sent to $recipient"?>-->
<!--readfile('submitResume.html');-->
<?php
header('Location: mailSend.html') ;
echo "Your mail successfully sent to $recipient"
?>
</div>
<?php
$recipient = "";
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
?>
<!-- display an alert message if somehow mail can't be sent -->
<div class="alert alert-danger text-center">
<?php echo "Failed while sending your mail!" ?>
</div>
<?php
}
}
}
}
?>
You are sending to a .html page, which does not process PHP code by default, the server just serves it unless specifically configured on the server. Rename the page from mailSend.html to mailSend.php and it should resolve it. Make sure to change your code to send to .php page.
For further reading see here
You would need to pass the message itself or a way for the script to know which message to show. The easiest way would be to pass it via $_GET, by attaching it to the end of the URL you are trying to redirect. Like so:
$target_url = mailSend.php;
$get_data = '?statusMsg=' . urlencode($statusMsg) . '&$msgClass=' . urlencode($msgClass);
header( 'Location: ' . $target_url . $get_data );
Which you can then recover on mailSend.php via the global $_GET variable. Such as:
$statusMsg = urldecode($_GET['statusMsg']);
$msgClass= urldecode($_GET['msgClass']);
There are other ways to get the data from one page to another but that I will leave it up to you to do research. As it is out of scope for a simple answer.

Error on contact form

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

Ajax Contact Form : Why is it not working?

I need some help with my code. So i am trying to create a contact form with PHP and AJAX. It works because it send me the email when i try but i was trying to show a sentence either if it worked or if it didn't work. I guess i am a bit lost and i would enjoy some hints from you guys !
Here is contact.js
$(submit).on("click", function(e){
e.preventDefault();
var formData = form.serialize();
$.ajax({
type : 'POST',
url : form.attr('action'),
data : formData,
dataType : 'json',
success: function(data){
console.log('success');
if(data.ciao == 'ok'){
console.log('success');
$('#nom').val('');
$('#prenom').val('');
$('#mail').val('');
$('#message').val('');
$(formMessage).removeClass('error');
$(formMessage).addClass('success');
$(formMessage).html('Mail envoyé avec succès');
}
},
error: function(){
if(data.ciao == "nope"){
console.log('erreur');
}
}
},"json");
})
});
`
Here is my contactController.php
public function envoiMailAction()
{
if($this->data){
$ciao = array();
$spam = htmlentities($this->data['sujetMessage']);
$nom = htmlentities($this->data['nom']);
$prenom = htmlentities($this->data['prenom']);
$mail = htmlentities($this->data['mail']);
$message = htmlentities($this->data['message']);
if(!empty($spam) && !($spam == '4' || strtolower($spam) == 'quatre'))
{
$ciao = 'nope';
Session::setFlash('Erreur SPAM' , 'danger');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
else
{
$handler = new stringHandler();
if($handler->checkInput($nom,NAME_MIN,NAME_MAX))
{
if($handler->checkInput($prenom,NAME_MIN,NAME_MAX))
{
if(filter_var($mail, FILTER_VALIDATE_EMAIL))
{
if($handler->checkMessage($message)){
$ip = $_SERVER["REMOTE_ADDR"];
$hostname = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
$destinataire = "amandine.dib#live.fr";
$objet = "Message de " . $prenom." ".$nom;
$contenu = "Nom de l'expéditeur : " . $nom . "\r\n";
$contenu .= $message . "\r\n\n";
$contenu .= "Adresse IP de l'expéditeur : " . $ip . "\r\n";
$contenu .= "DLSAM : " . $hostname;
$headers = "CC: " . $mail . " \r\n";
$headers .= "Content-Type: text/plain; charset=\"ISO-8859-1\"; DelSp=\"Yes\"; format=flowed /r/n";
$headers .= "Content-Disposition: inline \r\n";
$headers .= "Content-Transfer-Encoding: 7bit \r\n";
$headers .= "MIME-Version: 1.0";
$ciao = 'ok';
mail($destinataire, $objet, utf8_decode($contenu), 'From: amandine#exemple.com');
Session::setFlash('Message envoyé' , 'success');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
else
{
$ciao = 'nope';
Session::setFlash('Erreur message' , 'danger');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
}
else
{
$ciao = 'nope';
Session::setFlash('Erreur mail' , 'danger');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
}
else
{
$ciao = 'nope';
Session::setFlash('Erreur prenom' , 'danger');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
}
else
{
$ciao = 'nope';
Session::setFlash('Erreur nom' , 'danger');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
}
}
else{
$ciao = 'nope';
Session::setFlash('Erreur envoi impossible' , 'danger');
header('Location:index.php?controller=contact&action=afficherContact');
exit();
}
header('Content-type: application/json');
json_encode($ciao);
}
And my View :
<div class="container" style="width: 50%;">
<form action="index.php?controller=contact&action=envoiMail" id="formContact" method="post">
<div class="form-row">
<div class="form-group col-md-6">
<label for="Nom">Nom</label>
<input type="text" class="form-control" id="nom" name="nom" placeholder="Nom" required>
</div>
<div class="form-group col-md-6">
<label for="Prenom">Prenom</label>
<input type="text" class="form-control" id="prenom" name="prenom" placeholder="Prenom" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail4">Email</label>
<input type="email" class="form-control" id="mail" name="mail" placeholder="Email" required>
</div>
<div class="form-group sujetMessageBloc" style="display:none;">
<label for="sujetMessage">Combien font 2+2 ?</label>
<input type="text" class="form-control" id="sujetMessage" name="sujetMessage" placeholder="Combien font 2+2">
</div>
<div class="form-group">
<label for="corpsMessage">Votre message</label>
<textarea class="form-control" id="message" name="message" rows="3" required></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" id="submitForm" name="submit" value="Envoyer" />
</div>
</form>
<div id="formMessage"></div>
</div>
The array $ciao is there to tell me if yes or no it sent my email and then i want to get it in JSON so i can notify the user that the email was send or not. I get my email when i test it but i can't make the "notification" part works ! Thank you in advance for your help !
Look, there is no data.ciao. There is just data and data contains either "nope" or "ok".
Both of these two solution would work:
in contactController.php:
json_encode(['ciao' => $ciao]);
or in contact.js
if(data == 'ok'){
/* ... */
}
Just pick one of the solutions
Few things...
Output the JSON using echo json_encode($value).
If you are returning a JSON in your PHP and expecting a JSON in your JavaScript, then $value needs to be an array. $ciao (i.e. ok or nope) is not a JSON.
Don't redirect within your AJAX script when an error occurs. It won't work.
More of a personal opinion, sometimes it's better to return early rather than have nested IF statements.
Edit
After re-reading your post, it seems you want to remain on the same page and simply show the correct message depending on if the operation worked or not.
Simply, pass $ciao and $msg in your JSON. $ciao is used as a status flag to indicate if it worked or not and $msg is the message to show. On the client-side, when you get back the JSON response, you would check the JSON and make the appropriate HTML/CSS changes -- without having the need to do a reload of the page.
If that is not the case, simply check my original answer.
Example
PHP
public function envoiMailAction()
{
// always expecting a JSON to come back
header('Content-type: application/json');
if (!$this->data) {
echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur envoi impossible' ));
// if you are returning early in an AJAX script, you want to die or exit early
exit;
}
$spam = htmlentities($this->data['sujetMessage']);
$nom = htmlentities($this->data['nom']);
$prenom = htmlentities($this->data['prenom']);
$mail = htmlentities($this->data['mail']);
$message = htmlentities($this->data['message']);
if (!empty($spam) && !($spam == '4' || strtolower($spam) == 'quatre')) {
echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur SPAM' ));
exit;
}
$handler = new stringHandler();
// note the !
if (!$handler->checkInput($nom,NAME_MIN,NAME_MAX)) {
echo json_encode(array( 'ciao' => 'nope', 'message' => 'Erreur nom' ));
exit;
}
if (!$handler->checkInput($prenom,NAME_MIN,NAME_MAX)) {
echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur prenom' ));
exit;
}
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur mail' ));
exit;
}
if (!$handler->checkMessage($message)){
echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur message'));
exit;
}
// if we made it here, then it passed the validations
$ip = $_SERVER["REMOTE_ADDR"];
$hostname = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
$destinataire = "amandine.dib#live.fr";
$objet = "Message de " . $prenom." ".$nom;
$contenu = "Nom de l'expéditeur : " . $nom . "\r\n";
$contenu .= $message . "\r\n\n";
$contenu .= "Adresse IP de l'expéditeur : " . $ip . "\r\n";
$contenu .= "DLSAM : " . $hostname;
$headers = "CC: " . $mail . " \r\n";
$headers .= "Content-Type: text/plain; charset=\"ISO-8859-1\"; DelSp=\"Yes\"; format=flowed /r/n";
$headers .= "Content-Disposition: inline \r\n";
$headers .= "Content-Transfer-Encoding: 7bit \r\n";
$headers .= "MIME-Version: 1.0";
mail($destinataire, $objet, utf8_decode($contenu), 'From: amandine#exemple.com');
echo json_encode(array( 'ciao' => 'ok', 'msg' => 'Message envoyé' ));
}
JS
$(function () {
$(submit).on("click", function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
dataType: 'json',
success: function (data) {
// everything went well
if (data.ciao == 'ok'){
console.log('success');
$('#nom').val('');
$('#prenom').val('');
$('#mail').val('');
$('#message').val('');
$(formMessage).removeClass('error');
$(formMessage).addClass('success');
$(formMessage).html('Mail envoyé avec succès');
// something went bad and redirect to other page
} else {
$(formMessage).removeClass('success');
$(formMessage).addClass('error');
$(formMessage).html(data.msg);
}
}
});
})
});

mail not reached to my email id

i have this code in my contact page.
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/main.js"></script>
<script>
jQuery(document).ready(function() {
$("#submit").click(function()
{
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
//var pn = /^(\+91-|\+91|0)?\d{10}$/;
var email = $("#email").val();
var message = $("#message").val();
var subject = $("#subject").val();
var name = $("#name").val();
if(name=="")
{
//$('#empty1').show(1).delay(5000).fadeOut();
$('#name').focus();
return false;
}
else if(message=="")
{
//$('#empty4').show(1).delay(5000).fadeOut();
$('#message').focus();
return false;
}
else if(subject=="")
{
//$('#empty4').show(1).delay(5000).fadeOut();
$('#subject').focus();
return false;
}
else if(!(pattern.test(email)))
{
//$('#error2').show(1);
$('#email').focus();
}
else if(email=="")
{
//$('#empty2').show(1).delay(5000).fadeOut();
$('#email').focus();
return false;
}
else
{
var dataString = 'name='+ name + '&email=' + email + '&message=' + message + '&subject=' + subject;
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function(){
//$('.success').show('slide').delay(5000).fadeOut();
$("#contact-form")[0].reset();
alert("Your Detail Is Submitted, We Will Connect With You Soon.");
}
});
}
return false;
});
});
and i have form like that.
<form class="b-form b-contact-form m-contact-form" action="" style="margin-bottom: 10px;" id="contact-form">
<div class="input-wrap">
<i class="icon-user"></i>
<input class="field-name" type="text" placeholder="Name (required)" name="name" id="name">
</div>
<div class="input-wrap">
<i class="icon-envelope"></i>
<input class="field-email" type="text" placeholder="Email (required)" name="email" id="email">
</div>
<div class="input-wrap">
<i class="icon-pencil"></i>
<input class="field-subject" type="text" placeholder="Subject" name="suject" id="subject">
</div>
<div class="textarea-wrap">
<i class="icon-pencil"></i>
<textarea class="field-comments" placeholder="Message" name="message" id="message"></textarea>
</div>
<input class="btn-submit btn colored" type="submit" value="Submit Comment" id="submit" name="submit">
</form>
and also i have ajax mail.php page.
<?php
$to = "demo#example.com";
$subject = $_REQUEST["subject"];
$message = "message=".$_REQUEST["message"]."<br />";
$message .= "name=".$_REQUEST["name"]."<br />";
$message .= "email=".$_REQUEST["email"];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From:" .$_REQUEST["email"]. "\r\n";
mail($to,$subject,$message,$headers);
?>
i done servers mail forwarding setting, and also i check the ajax call, and what data will it parsing. using console apnel.
but i cant reached the mail in my email id.
please help me, what can i do now?
Here, give this a try.
Your message variables were not properly formatted and I modified your headers a bit.
This worked for me, minus your jQuery method.
<?php
$to = "demo#example.com";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
$message .= "" . "<br/>";
$message .= "name= $name" . "<br/>";
$message .= "email= $email" . "<br/>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if(mail($to,$subject,$message,$headers)){
echo "Success!!";
}
else {
echo "Sorry.";
}
?>

PHP form validation with AJAX

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('');
}
});

Categories