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()"
Related
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?
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);
}
}
});
})
});
I freeze all the fields on the form and then issue the mail when I press the submit button. There is a Turkish character problem at the output of mail.
contact.html
<div class="col-lg-6">
<div class="well">
<h3>İletişim Formu</h3>
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name">Ad Soyad</label>
<input type="text" class="form-control" id="name" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="telefon">Telefon</label>
<input type="text" class="form-control" id="telefon" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="konu">Konu</label>
<input type="text" class="form-control" id="konu" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="sektor">Sektör</label>
<select class="form-control" id="sektor" placeholder="" required data-error="Lütfen bu alanı doldurun.">
<option value="Özel" selected="selected">Özel</option>
<option value="Projeci">Projeci</option>
<option value="Satıcı">Satıcı</option>
<option value="Uygulayıcı">Uygulayıcı</option>
<option value="Diğer">Diğer</option>
</select>
</div>
<div class="form-group">
<label for="message">Mesajınız</label>
<textarea id="message" class="form-control" rows="5" placeholder="" required data-error="Lütfen bu alanı doldurun."></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Gönder</button>
<div id="msgSubmit" class="text-center hidden"></div>
<div class="clearfix"></div>
</form>
</div>
</div>
form-script.js
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Tüm alanları doldurdunuz mu?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var telefon = $("#telefon").val();
var konu = $("#konu").val();
var sektor = $("#sektor").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&telefon=" + telefon + "&konu=" + konu + "&sektor=" + sektor + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "text-center tada animated text-success";
} else {
var msgClasses = "text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
form-process.php
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// TELEFON
if (empty($_POST["telefon"])) {
$errorMSG .= "Telefon is required ";
} else {
$telefon = $_POST["telefon"];
}
// KONU
if (empty($_POST["konu"])) {
$errorMSG .= "Konu is required ";
} else {
$konu = $_POST["konu"];
}
// SEKTOR
if (empty($_POST["sektor"])) {
$errorMSG .= "Sektor is required ";
} else {
$sektor = $_POST["sektor"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "simple#mail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Telefon: ";
$Body .= $telefon;
$Body .= "\n";
$Body .= "Konu: ";
$Body .= $konu;
$Body .= "\n";
$Body .= "Sektör: ";
$Body .= $sektor;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Mail Output
Name: Ahmet
Email: ahmetcadi#gmail.com
Telefon: 05636588110
Konu: üğ
Sektör: Özel
Message: üğiğ
Try adding charset parameter to your AJAX request, like so:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&telefon=" + telefon + "&konu=" + konu + "&sektor=" + sektor + "&message=" + message,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
Insert
<meta charset="utf-8"/>
at the top of your Head section. Example usage :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
...etc
</head>
...
Solution of the problem. Erol Keskin Thank you.
$success = mail($EmailTo, '=?utf-8?B?'.base64_encode($Subject).'?=', $Body, 'MIME-Version: 1.0' . "<br>".'Content-type: text/html; charset=utf-8' . "<br>".'From: '.$email . "\r\n");
This is output in the email so you need to set the relevant header there as well; currently you're only setting the From header.
// send email
$success = mail(
$EmailTo,
$Subject,
$Body,
"From: {$email}\r\nContent-Type: text/plain;charset=utf8"
);
See the section on Additional Headers : http://php.net/manual/en/function.mail.php
As an aside, depending on the mailserver you may need to tweak your line terminators in the header string - Postfix expects them to be in the format relevant to the OS, so \n on *nix systems. It's unlikely to break anything but...
How can I verify that the contact number a user inputs in the contact form is in fact numbers and they are at least 10 numbers? Meaning I want the input field only accept 10 numbers or more and also accept the plus (+) sign. At the moment the php verifies that the all fields are completed and the email correct.
here is the html code:
<div class="contact-form">
<form id="contact-form" action="sendmail.php" method="post" title="Contact Form" role="form">
<div class="col-sm-6">
<div class="form-group">
<label for="contact-name">Full name</label>
<input type="text" name="name" placeholder="Enter your full name..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-email">Email</label>
<input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email">
</div>
<div class="form-group">
<label for="contact-number">Contact number</label>
<input type="text" name="number" class="active" id="contact-number" placeholder="Your contact number...">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="contact-message">Message</label>
<textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message"></textarea>
</div>
</div>
<div class="col-sm-12 text-center">
<button type="submit" class="btn btn-default sketchFlowPrint" id="submit">Send</button>
</div>
</form>
</div>
here is the php code:
<?php
// Email address verification
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
$subject = 'Query from My Domain';
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($number == '') {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
here is the jQuery:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var numberLabel = form.find('label[for="contact-number"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Full name');
emailLabel.html('Email');
numberLabel.html('Contact number');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.numberMessage !== '') {
numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});
I'm guessing that the + needs to be the first character (international phone numbers)?
Then this should do it:
if (!preg_match('/^(\+?)+([0-9]{10,})$/', $number)) {
$array['numberMessage'] = 'Please enter a valid contact number.'
}
The plus sign is optional. If it should be required, just remove the ? after the plus sign in the expression.
Check the length is less than 10 or see if the input differs from the filtered input (+ and digits removed).
<?php
function valid_tel($in) {
$valid = true;
if(strlen($in) < 10 || $in !== preg_replace('#[^0-9+]#','', $in)) {
$valid = false;
}
return $valid;
}
var_dump(valid_tel(''));
var_dump(valid_tel('01234'));
var_dump(valid_tel('01234567890')); // 11 long
var_dump(valid_tel('+012345678')); // 10 inc +
var_dump(valid_tel('+0123456'));
var_dump(valid_tel('0123456xyz7890'));
Output:
boolean false
boolean false
boolean true
boolean true
boolean false
boolean false
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.";
}
?>