I request your kind help with this problem. I have a website with the respective contact form, but it has never worked for me. The messages do not arrive. Sending them the contact page send_mail.php file and everything related. I thank you very much the help and detailed explanation as this topic is very complex.
Contact.js
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
}else{
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#button').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Submit');
}
});
}
});
});
Send_mail.php
require_once 'google/appengine/api/mail/Message.php';
use google\appengine\api\mail\Message;
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$message_body = "...";
$mail_options =[;
"sender" => "administrador#formarchivos.com",
"to" => $email,
"subject" => $subject,
"textBody" => $message_body
];
try {
$message = new Message($mail_options);
$message->send();
echo 'sent';
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
echo 'failed';
}
Contact.html
<!-- Contact Form -->
<form action="send_email.php" method="post" id="contact_form">
<h3>Ficha de contacto</h3>
<div class="hr dotted clearfix">
<h3> </h3>
</div>
<ul>
<li class="clearfix">
<h3>
<label for="name">Nombre</label>
<input type='text' name='name' id='name' />
</h3>
<div class="clear"></div>
<h3 id='name_error' class='error'>Inserte un nombre</h3>
</li>
<li class="clearfix">
<h3>
<label for="email">Email </label>
<input type='text' name='email' id='email' />
</h3>
<div class="clear"></div>
<h3 id='email_error' class='error'>Ingrese una cuenta de correo valida</h3>
</li>
<li class="clearfix">
<h3>
<label for="subject">Tema</label>
<input type='text' name='subject' id='subject' />
</h3>
<div class="clear"></div>
<h3 id='subject_error' class='error'>Ingrese un Tema para su mensaje</h3>
</li>
<li class="clearfix">
<h3>
<label for="message">Mensaje</label>
<textarea name='message' id='message' rows="30" cols="30"></textarea>
</h3>
<div class="clear"></div>
<h3 id='message_error' class='error'>Ingrese su mensaje</h3>
</li>
<li class="clearfix">
<h3 id='mail_success' class='success'>Gracias. Nosotros te responderemos tan pronto como nos sea posible.</h3>
<h3 id='mail_fail' class='error'>Disculpenos, un error ha ocurrido. Por favor intentelo despues.</h3>
<div id="button">
<h3>
<input type='submit' id='send_message' class="button" value='Enviar' />
</h3>
</div>
<!--end wrapper-->
<div align=center></div></body>
</html>
This is all that I have, I have nothing mensaje.php, if I may not need any extra file to be honest I do not know where can be the error.
Aside from your syntax error suggested by #koljanep I have a couple suggestions/comments:
Have you tried doing a function (perhaps even on the php page) to handle your
jQuery errors instead of repeating a bunch of same fade effects?
Maybe sanitize your inputs on the PHP page.
Perhaps a more straight-forward AJAX would help.
You assign
$message = $_POST['message']; but then you assign $message = new
Message($mail_options); so there is some weirdness going on
there...
Contact.js
$(document).ready(function(){
$('#contact_form').submit(function(e){
$.ajax({
url:"Send_mail.php",
type: 'POST',
data: $("#send_message").serialize(),
success: function(data) {
// This id would have to be somewhere on your page
// to drop into (I'm sure you know that)
$("#response").html(data);
}
});
return false;
});
});
Send_mail.php
<?php
// Do some basic sanitizing...I chose preg_replace, but you can do whatever
$setting['name'] = (!empty($_POST['name']))? preg_replace('/[^0-9a-zA-Z\.\']/'," ",$_POST['name']):0;
$setting['subject'] = (!empty($_POST['subject']))? preg_replace('/[^0-9a-zA-Z\.\']/'," ",$_POST['subject']):0;
$setting['message'] = (!empty($_POST['message']))? strip_tags($_POST['message']):0;
// Check first that the email is a valid one!
if(isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// If all checks out,
if(!in_array(0,$setting)) {
require_once('google/appengine/api/mail/Message.php');
use google\appengine\api\mail\Message;
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$message_body = "...";
$mail_options = [
"sender" => "administrador#formarchivos.com",
"to" => $email,
"subject" => $subject,
"textBody" => $message.$message_body
];
try {
$sendMessage = new Message($mail_options);
$sendMessage->send();
echo 'sent';
}
catch (InvalidArgumentException $e) {
echo $e->getMessage();
echo 'failed';
}
}
else
$_error = $setting;
}
else {
$setting['email'] = 0;
$_error = $setting;
} ?>
<script>
function ReturnError(IdVal) {
$('#'+IdVal+"_error").fadeIn(500);
}
<?php
if(isset($_error)) {
foreach($_error as $key => $errored) {
if($errored == 0) { ?>
ReturnError('<?php echo $key; ?>');
<?php }
}
} ?>
</script>
Related
I am following a guide to build a bootstrap contact form and submit it through mail.php without having to reload the page using ajax. I am able to get the form to work up until I try implementing ajax. I get stuck because the instructions arent clear as to which code exactly needs to be replaced and where the new code is supposed to go. Here is a link to the guide I am following and the section I am stuck at:
Sending email without reloading page using AJAX
This is the site I am trying to get it to work on: CRANE TECH. NET
I am not so familiar with php so I'm thinking that is where I am messing it up at.
Here is the exact code I am using:
HTML
<section class="section">
<h2 class="section-heading text-muted h4 pt-4">Free Consultation</h2>
<!--CONTACT DESCRIPTION-->
<p class="section-description">Are you ready to turn your vision into a reality? Fill out the contact form below and a member of our team will get back to you as soon as possible. Let's bring your idea to life!</p>
<div class="row">
<div class="col-12">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row">
<!--NAME INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="* NAME" required>
<label for="name" class=""></label>
</div>
</div>
<!--EMAIL INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="email" name="email" class="form-control" placeholder="* EMAIL" required>
<label for="email" class=""></label>
</div>
</div>
</div>
<div class="row">
<!-- PHONE NUMBER INPUT -->
<div class="col-12">
<div class="md-form">
<input type="text" id="clientPhone" name="clientPhone" class="form-control" placeholder="PHONE" required>
<label for="phone number" class=""></label>
</div>
</div>
<!--SUBJECT INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="subject" name="subject" class="form-control" placeholder="* SUBJECT" required>
<label for="subject" class=""></label>
</div>
</div>
</div>
<div class="row">
<!--MESSAGE INPUT-->
<div class="col-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="3" class="form-control md-textarea" placeholder="* MESSAGE" required></textarea>
<label for="message"></label>
</div>
</div>
</div>
</form>
<!-- SUBMIT BUTTON -->
<div class=" col-3 offset-3 offset-md-4 mb-4">
<button class="btn btn-warning" onclick="validateForm()">Send <i class="fa fa-paper-plane ml-1"></i></button>
</div>
<div id="status" class="text-muted col-12 col-md-8 offset-md-2 my-1"></div>
</div>
JS
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
return false;
} else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(email)) {
document.getElementById('status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
return false;
}
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'clientPhone': $('input[name=clientPhone]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
document.getElementById('contact-form').submit();
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
}
MAIL.PHP
<?php
if(isset( $_POST['name']))
$name = $_POST['name'];
if(isset( $_POST['email']))
$email = $_POST['email'];
if(isset( $_POST['clientPhone']))
$clientPhone = $_POST['clientPhone'];
if(isset( $_POST['subject']))
$subject = $_POST['subject'];
if(isset( $_POST['message']))
$message = $_POST['message'];
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
// if ($name === ''){
// echo "Name cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($email === ''){
// echo "Email cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// } else {
// if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
// echo "Email format invalid.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// }
// if ($subject === ''){
// echo "Subject cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($message === ''){
// echo "Message cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
$content="From: $name \n Email: $email \n Phone #: $clientPhone \n Subject: $subject \n Message: $message";
$recipient = "support#crane-tech.net";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!', 'code' => 1));
exit();
?>
Main Issue
You main issue is that there is a missing semcolon (;) and the end of line 15 in the php code.
Other Issues
Your website is using JQuery Slim, $.ajax is not included in the slim version so you are getting an error due to that. To fix this just include the full JQuery or do the ajax without JQuery.
You may also want to get rid of this line:
document.getElementById('contact-form').submit();
because it is causing a redirect when you are already manually submitting your data.
You should remove these lines because you have already set them:
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
Unrelated note:
If you are already using JQuery, you should be using it - instead of doing this:
document.getElementById('status')
You should be using:
$('#status')
I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php
I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.
I downloaded a wordpress template (http://themes.tvda.eu/demos/identiq/) but I must've screwed up the contact form, not sure how. Could anyone enlighten me please?
It's also on https://github.com/fileradar/fileradar.github.io if easier.
Many thanks
<!-- Start Contact Page -->
<section id="contact" class="page">
<div class="container">
<div class="row">
<div class="span12">
<hr class="feedbackline">
<div class="result">
</div>
</div>
</div>
<!-- Start Form -->
<form class="well">
<div class="row">
<div class="span6 pull-left">
<label>Your name</label>
<input class="span6" type="text" name="name" placeholder="Your Name">
</div>
<div class="span6 pull-right">
<label>Your e-mail</label>
<input class="span6" type="text" name="email" placeholder="Your E-mail">
</div>
</div>
<div class="row">
<div class="span12 textarea-margin">
<label>Message</label>
<textarea class="span12" rows="8" name="message" placeholder="Message"></textarea>
<button type="submit" class="btn"><i class="web-icon">8</i>Send Message</button>
</div>
</div>
</form>
<!-- End Form -->
</div>
</section>
<!-- End Contact Page -->
Then the js file is:
$(function()
{
$("#contact form").submit(function()
{
var form = $(this);
var str = form.serialize();
$.ajax(
{
type: "POST",
url: "contact.php",
data: str,
success: function(msg)
{
$("#contact .result .alert").remove();
msg = JSON.parse(msg);
if(msg.status == 'OK')
{
$('#contact .result').append('<div class="alert alert-success">Your message has been sent. Thank you!</div');
}
else if(msg.text)
{
$.each(msg.text, function(i, elem){
$('#contact .result').append('<div class="alert alert-error">' + elem + '</div');
})
}
else
{
$('#contact .result').append('<div class="alert alert-error">Error</div');
}
}
})
return false;
})
})
and the two php's are:
<?php
function ValidateEmail($email)
{
/*
(Name) Letters, Numbers, Dots, Hyphens and Underscores
(# sign)
(Domain) (with possible subdomain(s) ).
Contains only letters, numbers, dots and hyphens (up to 255 characters)
(. sign)
(Extension) Letters only (up to 10 (can be increased in the future) characters)
*/
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){1,255}'. # domain & possibly subdomains
'.'. # period
"([a-z]+){2,10}/i"; # domain extension
if($email == '') {
return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}
return empty($eregi) ? true : false;
}
?>
and
<?php
include 'contact_config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$message = stripslashes($_POST['message']);
$error = array();
// Check name
if(!$name)
{
$error[] = 'Please enter your name.';
}
// Check email
if(!$email)
{
$error[] = 'Please enter an e-mail address.';
}
if($email && !ValidateEmail($email))
{
$error[] = 'Please enter a valid e-mail address.';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error[] = "Please enter your message. It should have at least 15 characters.";
}
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
mail($to, $message, $headers);
if($mail)
{
echo json_encode(array('status' => 'OK'));
}
else
{
echo json_encode(array('status' => 'error', 'text' => array('Error')));
}
}
else
{
echo json_encode(array('status' => 'error', 'text' => $error));
}
}
?>
I have been created subscribe button using php,
Html:
<div id="newsletterform">
<h2>Get Email Update</h2>
<form action="send.php" method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<input type="submit" value="Subscribe" name="signup-button" id="signup-button">
<span class="arrow"></span>
</form>
<div id="response"></div>
</div>
Now i had been found some click effect of buttons, here is the link, http://tympanus.net/Development/CreativeButtons/
In the above, 7th section[green color section], it has two submit form buttons.
One for success and one for error, so i need to use them in my subscribe form, i mean move to my send.php.
So when i click subscribe button without enter email, it shows button says, "error" instead, notification.
May i know, is it possible to achieve this?
Any help would be highly appreciated.
there is an easy way to ding so you place both two button and give error button to css display:none;
as in jquery
else {
$status = "error";
$message = "An error occurred, please try again";
$('.button-error').show();
$('.button-success').hide();
}
in this way you can achieve what you want
Download and place component.css in css folder, then add this to <head>:
<link rel="stylesheet" type="text/css" href="css/component.css" />
HTML :
<div id="newsletterform">
<h2>Get Email Update</h2>
<form method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<input type="submit" value="Subscribe" name="signup-button" id="signup-button" class="btn btn-7 btn-7h icon-envelope">
<span class="arrow"></span>
</form>
<div id="response">
<?php if (isset($_POST['signup-button']) { ?>
<span color="<?=($status=='success')?'green':'red';?>"><?=$message;?></span>
<?php } ?>
</div>
</div>
And place just before closing </body>:
<?php if ($status == "error") { ?>
<script>
document.getElementById('signup-button').className = "btn btn-7 btn-7h icon-envelope btn-error";
setTimeout(function() {
document.getElementById('signup-button').className = "btn btn-7 btn-7h icon-envelope";
}, 1000);
</script>
<?php } ?>
Put the following at the top of your footer.php or index.php (in which you include() the footer.php)
<?php
if (isset($_POST['signup-button'])) {
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
Also have a look here :
http://jsfiddle.net/8ft0ye6k/3/
Hope it helps.
Use this Demo Here
Add this css and js this should works
<link rel="stylesheet" type="text/css" href="http://tympanus.net/Development/CreativeButtons/css/default.css" />
<link rel="stylesheet" type="text/css" href="http://tympanus.net/Development/CreativeButtons/css/component.css" />
<script src="http://tympanus.net/Development/CreativeButtons/js/modernizr.custom.js"></script>
<script src="http://tympanus.net/Development/CreativeButtons/js/classie.js"></script>
$status = "<button class="btn btn-1 btn-1a">Button</button>";
$message = "An error occurred, please try again";
$status = "<button class="btn btn-1 btn-1a">Button</button>";
$message = "This email is already subscribed";