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));
}
}
?>
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 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>
This question already has answers here:
PHP Redirect to another page after form submit
(6 answers)
Closed 8 years ago.
So after I used the new JavaScript. Here is all of the code. Just keep in mind their is still top body missing. Didn't put that in as it might not be relevant to my problem.
<?php
// define variables and set to empty values
$nameErr = $surnameErr = $emailErr = $contact_numberErr = "";
$name = $surname = $email = $comment = $contact_number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["contact number"])) {
$contact_numberErr = "Please provide contact details";
} else {
$contact_number = test_input($_POST["contact number"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contact_number)) {
$contact_number = "Only numbers allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container" align="center">
<div class="row featured-boxes login">
<div class="col-md-6">
<div class="featured-box featured-box-secundary default info-content">
<div class="box-content">
<h4 align="center">Customer Feedback</h4>
<p><span class="error">* required field.</span></p>
<form method="post" action="insert_customer_feedback.php" name="customer_feedback">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Name</label> *<?php echo $nameErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtName" name="txtName">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Surname</label> *<?php echo $surnameErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtSurname" name="txtSurname">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>E-mail</label> *<?php echo $emailErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtEMail" name="txtEmail">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Contact Number</label> *<?php echo $contact_numberErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtContact_number" name="txtContact_number">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Comment</label>
<input type="text" value="" class="form-control input-lg" id="txtComment" name="txtComment">
</div>
</div>
<input type="button" value="Submit" class="btn btn-primary pull-right push-bottom" onClick="Confirm(this.form)">
</div>
</div>
</form>
<script type="text/javascript">
function Confirm(form){
alert("Thank you for your feedback.");
form.submit();
window.location.href = "/index.php";
}
</script>
For some reason it does not want to load my data into MySQL when having this peace of JavaScript (window.location.href = "/index.php";) added.
you can simply do it using
function Confirm(form){alert("Thank you for your feedback.");form.submit();
window.location = "location";
}
If you want to do the redirect in JavaScript it would be:
window.location.replace("yourwebsite.com/index.php");
If you wanted to do it in PHP, then it would be:
header('Location:index.php');
When you do the form.submit() you tell the form to perform the action which is stated in the forms action attribute. Thus it will automatically be redirected to whatever is set there.
Example:
<form action="submit.php" method="POST">
You code will redirect the user to the submit.php after he dismisses the alert message. When redirected to the submit.php you will have to handle a redirect from there on.
This is of course unless you are using AJAX to post the form or something like that.
Then you can just add:
window.location.href = "/index.html";
Although, in that case, it would better be placed in the success-function of the AJAX call:
function Confirm(form){alert("Thank you for your feedback.");form.submit(); window.location.href = "/index.html";}
I do not receive any emails when my webform is filled out. It does not give me any errors. Code posted below:
HTML form:
<div class="col-md-6">
<h3>General Questions? <p class="h4">Use our form.</p></h3>
<address>Required fields are marked with an *.</address>
<div class="col-md-12">
<form data-toggle="validator" role="form" class="form-horizontal" id="contactForm">
<!-- Name-->
<div class="form-group">
<label for="inputName" class="control-label"><span class="glyphicon glyphicon-user">
</span> Name * </label><input type="text" class="form-control" id="inputName"
placeholder="What's your name?" data-errors="We need to know what to call you!" required>
<div class="help-block with-errors"></div>
</div>
<!-- Email-->
<div class="form-group">
<label for="inputEmail" class="control-label"><span class="glyphicon glyphicon-
envelope"></span> Email *</label>
<input type="email" class="form-control" id="inputEmail" placeholder="example#example.com"
data-errors="This email address is invalid" required>
<div class="help-block with-errors"></div>
</div>
<!-- Phone Number-->
<div class="form-group">
<label for="inputNumber" class="control-label"><span class="glyphicon glyphicon-phone-
alt"></span> Phone Number</label>
<input type="text" class="form-control" id="inputNnumber" data-minlength="9"
placeholder="(123) 867-5309">
</div>
<!-- Textarea -->
<div class="form-group">
<label for="inputMessage" class="control-label"><span class="glyphicon glyphicon-pencil">
</span> Message *</label>
<textarea rows="8" class="form-control" placeholder="How can we help?" data-errors="We
can't help if you don't tell us how!" required>
</textarea>
<div class="help-block with-errors"></div>
</div>
<!-- Select Basic -->
<div class="control-group text-center">
<span><span class="glyphicon glyphicon-question-sign"></span> <strong>How should we
contact you?</strong></span><br>
<input type="radio" name="contact" value="phone"> by phone
<input type="radio" name="contact" value="email"> by email
</div>
<!-- Button -->
<br>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-sm btn-block">Submit</button>
</div>
</form>
</div>
</div>
Javacript: (it's at devnew.company.com/mail.php and will eventually be at company.com/mail.php. Am I correct in leaving it at /mail.php here?)
var mailUrl = "/mail.php";
var formId = "contactForm";
var completeHTML = ' <div class="alert alert-primary"> Sent! Thanks, we will be in touch
soon. </div> ';
function submitForm(){
$.ajax({
url : mailUrl,
type: 'post',
data:{
inputName : $('#inputName').val(),
inputEmail : $('#inputEmail').val(),
inputNumber : $('#inputNumber').val(),
inputMessage : $('#inputMessage').val(),
contact : $('input[name="contact"]:checked').val()
}
});
}
$(function(){
$('#contactForm').submit(function(){
submitForm();
$(this).html( completeHTML );
return false;
})
})
PHP
<?php
if (isset($_POST['Submit'])) {
if ($_POST['inputName'] != "") {
$_POST['inputName'] = filter_var($_POST['inputName'], FILTER_SANITIZE_STRING);
if ($_POST['inputName'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
if ($_POST['inputEmail'] != "") {
$email = filter_var($_POST['inputEmail'], FILTER_SANITIZE_EMAIL);
if (!filter_var($inputEmail, FILTER_VALIDATE_EMAIL)) {
$errors .= "$inputNumber is not a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
if ($_POST['inputNumber'] != "") {
$homepage = filter_var($_POST['inputNumber'], FILTER_SANITIZE_NUMBER_INT);
if ($_POST['inputNumber'] == "") {
$errors .= "Please enter 9 digits.<br/><br/>";
}
} else {
$errors .= 'Please enter your phone number.<br/>';
}
if ($_POST['inputMessage'] != "") {
$_POST['inputMessage'] = filter_var($_POST['inputMessage'],
FILTER_SANITIZE_STRING);
if ($_POST['inputMessage'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
if ($_POST['radio'] != "") {
$_POST['radio'] = filter_var($_POST['radio'], FILTER_SANITIZE_STRING);
if ($_POST['inputName'] == "") {
$errors .= 'Please choose an option.<br/><br/>';
}
} else {
$errors .= 'Please choose one.<br/>';
}
if (!$errors) {
$mail_to = 'rnunley#remedypartners.com';
$subject = 'New Mail from Form Submission';
$message = 'From: ' . $_POST['inputName'] . "\n";
$message .= 'Email: ' . $_POST['inputEmail'] . "\n";
$message .= 'Homepage: ' . $_POST['inputNumber'] . "\n";
$message .= "Message:\n" . $_POST['inputMessage'] . "\n\n";
$message .= 'Contact choice: ' . $_POST['radio'] . "\n";
mail($to, $subject, $message);
echo "Thank you for your email, we'll be in touch!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
}
?>
From your code, it doesn't look like you are sending a Submit variable in your ajax data. If that is the case, then your PHP will fail your initial if statement. You could try to add a print_r($_POST); at the beginning of your PHP and then watch the browser console to see what PHP is receiving.
It could be that your javascript thinks that the variables you are trying to pass are being read as non existent javascript vars
below is what maybe could work
$.ajax({
url : mailUrl,
type: 'post',
data:{
"inputName" : $('#inputName').val(),
"inputEmail" : $('#inputEmail').val(),
"inputNumber" : $('#inputNumber').val(),
"inputMessage" : $('#inputMessage').val(),
"Submit" : "TRUE",
"contact" : $('input[name="contact"]:checked').val()
},success: function (data) {
alert(data);
}
});
and add this on the beginning of your mail.php
foreach($_POST as $key => $value){
$content .= $key.' : '.$value;
}
echo $content
Too see what you are recieving on your mailurl