Ajax Contact Form : Why is it not working? - php

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

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 mail form with submit message fade in

My PHP email form code is working though, but the output after submitting the message is not correct.
After sending a message it is poping an “OK” echo on a blank page (URL www.domain.com/mailform.php), instead of fading out the contact form on the page and fading in the “successful sent” message, without changing the URL.
Where is the bug in the code? :(
HTML
<div class="contact-form-grid">
<form method="post" name="contactForm" id="contactForm" action="sendEmail.php">
<div class="fields-grid">
<div class="styled-input agile-styled-input-top">
<input type="text" for="contactName" id="contactName" name="contactName" required="" />
<label>Dein Name</label></div>
<div class="styled-input agile-styled-input-top">
<input type="text" for="contactTel" name="contactTel" required="" />
<label>Telefon</label></div>
<div class="styled-input">
<input type="email" for="contactEmail" id="contactEmail" name="contactEmail" required="" />
<label>E-Mail</label></div>
<div class="styled-input">
<input type="text" for="contactSubject" id="contactSubject" name="contactSubject" required="" />
<label>Betreff</label></div>
<div class="clearfix"></div>
</div>
<div class="styled-input textarea-grid">
<textarea name="contactMessage" required=""></textarea>
<label>Schreibe hier deine Nachricht!</label></div>
<input type="submit" value="Senden" />
<div id="submit-loader">
<div class="text-loader">Senden...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</form>
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">Ihre Nachricht wurde abgeschickt, danke!
<br /></div>
</div>
PHP
<?php
// Replace this with your own email address
$siteOwnersEmail = 'myemail#gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$tel = trim(stripslashes($_POST['contactTel']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Bitte geben Sie Ihren Namen ein.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Bitte geben Sie eine korrekte E-Mail-Adresse ein.";
}
// Subject
if ($subject == '') { $subject = "Anfrage"; }
// Set Message
$message .= "<strong>" . "Absender: " . "</strong>". $name . "<br />";
$message .= "<strong>" . "Email: " . "</strong>" . $email . "<br /><br />";
$message .= "<strong>" . "Telefon: " . "</strong>" . $tel . "<br /><br />";
$message .= "Nachricht: <br />";
$message .= $contact_message . "<br />";
$message .= "<br /> ----- <br /><i> Gesendet von .... </i></font><br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
if (!$error) {
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Etwas ging schief! Probiere später nochmal."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
JS
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Etwas ging schief! Probiere später nochmal.");
$('#message-warning').fadeIn();
}
});
}
});
I hope someone can help me here :(
Your error is probably in your javascript, is the page refreshing before saying "OK"?
A simpler way to submit a form with ajax is:
$("#form").ajaxForm({
url: "",
beforeSubmit: function() {
},
success: function() {
},
error: function() {
}
});
Did you try this?

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

Sending json to php server using jquery ajax - json error

I have problem with my form on my webpage. I am trying to use ajax and json to send the form values to php server, but I can't make properly json object.
My JS code
function sendJsonOpenPopout () {
$('.submitBtn').click(function(e){
e.preventDefault();
var subject = $('.subject').val();
var email = $('.email').val();
var message = $('.message').val();
var dataObject = {
subject: subject,
email: email,
message: message
}
$.ajax({
type: 'POST',
url: '../../kontakt.php',
contentType: "application/json",
dataType: 'json',
data: dataObject,
success: function(data){
alert('Items added');
},
error: function(){
console.log('You have fail');
}
//success: function(){
//var createdDiv = '<div class="divToBeCentered"><p class="dataText">Wiadomość została wysłana pomyślnie.\brDziękuję za kontakt.</p></div>';
//$('body').append(createdDiv);
//}
});
});
My PHP code
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$subject = $response[0];
$from = $response[1];
$message = $response[2];
$to = "lubycha#gmail.com";
$subject = $_POST['subject'];
$from = $_POST['email'];
$message = $_POST['message'];
$headers = "Content-Type: text/html; charset=UTF-8";
mail($to,$subject,$message,$headers);
?>
I know there is similar question already asked, but the answers didn't help me.
Thanks for helping.
I was able to get the json object and parse it on php side. Some variable might be named different, partly because some of it is pre-written code. Here are the steps I took.
Folder Structure
js/script.js
php/get_data.php
index.html
Index.html
a basic form.
<div id="feedback_panel" class="panel panel-default">
<form id="feedbackform" name="feedbackform" method="post">
<div class="form-group" id="email_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="email">E-mail:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="email#example.com" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="subject_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="subject">Subject:</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="description_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="message">message:</label>
<textarea type="text" class="form-control" id="message" name="message" placeholder="message." required></textarea>
<span class="help-block"> </span>
</div>
<button type="submit" id="feedback_submit" class="btn btn-success">Submit</button>
</form>
</div>
script.js
upon submit, gather data and set it to an object and send to php via ajax.
$(function() {
// process the form
$('#feedbackform').submit(function(event) {
// get the form data - obj that will POSTED to get_data.php
var formData = {
'email' : $('#email').val(),
'subject' : $('#subject').val(),
'message' : $('#message').val()
};
// process the forum
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'php/get_data.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
if ( ! data.success) {
console.log(data);
} else {
console.log(data);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
get_data.php
receives the data from script.js, do some validations, and then send and an e-mail.
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
$email;
$subject;
$message;
//check to see if the data exist, else write an error message,
function check_data(){
$user_inputs = array();
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
return false;
}else{
$email = $_POST['email'];
array_push($user_inputs,$email);
}
if (empty($_POST['subject'])){
$errors['subject'] = 'subject is required.';
return false;
}else{
$subject = $_POST['subject'];
array_push($user_inputs,$subject);
}
if (empty($_POST['message'])){
$errors['message'] = 'message is required.';
return false;
}else{
$message = $_POST['message'];
array_push($user_inputs,$message);
}
return $user_inputs;
}
//getting array of data from check_data
$verify_data = check_data();
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
} else {
// show a message of success and provide a true success variable
$data['success'] = $verify_data;
$data['message'] = 'Success!';
//if everything is good, sent an email.
if($verify_data != false){
send_email($verify_data);
}
}
function send_email($info_data){
// person who it going
$to = 'Email, Some <some_email#mailinator.com>';
//subject of the email
$subject = $info_data[1];
$result = str_replace(' ', ' ', $info_data[2]);
$result = nl2br($result);
$result = wordwrap($result, 70, "\r\n");
//body of the email.
$message = "<html><body>";
$message .= "<p style = 'width: 400px;'>" . $result . "</p>";
$message .= "<br/>";
$message .= "</body></html>";
$headers = "From: Email, Some <some_email#mailinator.com>" . "\r\n" . 'Reply-To: '. $info_data[0] . "\r\n" ."X-Mailer: PHP/" . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
//sent mail: check to see if it was sent.
if(mail($to, $subject, $message, $headers)){
$data["went"] = "went";
$data['message'] = 'Success!';
}else{
$data["went"] = "didn't go";
$data['message'] = 'Sorry!';
}
// echo the log
echo json_encode($data);
}
?>
lot to cover, let me know if you any questions. I'll be happy to answer.

Categories