How to add a 'Send Message To' button on contact page? - forms

I'm trying to add a "Send Message To" button on a contact form but I'm having trouble with the javascript/PHP. I'm using code I edited that came with the start bootstrap modern business theme, so far I have just added the $to = '$department', set the select tag ID as department and the value of option tags to the appropriate emails.
Not sure if any of that is correct.
HTML:
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Send Message To</label>
<select class="form-control" id="department">
<option value="sales#website.com">Sales</option>
<option value="support#website.com">Support</option>
</select>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-CMD" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
PHP:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$message = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = '$department';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Javascript
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});

Im not quite sure about your questions, but if you're just trying to get the item from the department form, and send it to that email address, this is the code for that.
JS:
data: {
name: name,
email: email,
message: message,
department: document.getElementById('department').value
},
You must pass the value of the form to the PHP script. You originally had the $message var set to the message and then the next line would set that variable to the department. You need to keep them separate.
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$department = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = $department;
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Hope this works!

Related

Codeigniter appears to always set validation->run to FALSE

Controller : User.php
public function index()
{
log_message('debug', ' Index User');
die("should never get here");
}
public function login()
{
log_message('debug', ' Login Entered');
echo '<pre> Printing Login data:';
print_r($_POST);
echo "</pre>";
$data['pageHeader'] = "Login";
$data['message'] = 'temporary message - This will be the login stuff';
$this->session->set_flashdata('flashInfo', 'Login form will go here');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE)
{
log_message('debug', ' validation run FALSE');
$this->load->helper('form');
$this->render_page('user/login', 'public_header', 'footer', $data);
}
else
{
log_message('debug', ' validation run TRUE');
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember))
{
log_message('debug', ' redirect Dashboard');
redirect('dashboard');
}
else
{
$_SESSION['auth_message'] = $this->ion_auth->errors();
$this->session->mark_as_flash('auth_message');
log_message('debug', ' redirect user login');
redirect('user/login');
}
}
}
Known from log:
function login entered,
$_POST always 'empty',
form validation-> always FALSE thus debug message is logged and form redisplayed
Form user/login.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<div class="container">
<?php echo $message;?>
<h1>Login</h1>
<form action="#" method="post">
<div class="imgcontainer">
<img src="http://www.hdkumdo.com/smen/assets/crow2.png" alt="Swordsmen Martial Arts">
</div>
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" required autofocus>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<button type="submit" name="login" id="login" value"login" >Login</button>
<label>
<input type="checkbox" checked="checked" name="remember" id="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
Copied an example from https://www.codeigniter.com/user_guide/libraries/form_validation.html
and form posts data but if I change function index to login it does not work.
Menu link : Login works fine.
Everything seems to be connected...login form displays, Controller function login is entered but it seems like there is no POST data so the form is simply redisplayed. I have 2 simple validation rules so it seems that validation->run should return true if I just enter any data into the fields.
I am sure it's something simple but for the life of me I can't see what.
First of all make sure you have loaded form validation library
$this->load->library('form_validation');
//set field validation
$this->form_validation->set_rules('fieldname','Field Name','required');
if($this->form_validation->run())
{
//then process form
//redirect
}
else {
//load view
}

PHPMailer and Ionic with Gmail

I'm attempting to create a contact form for my app using PHPMailer and Ionic with Gmail.
The page receives (Failed.) result message when it triggers the script but I never get the email from the form. Here is my code:
template.html
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
app.js
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed.';
$scope.result='bg-danger';
}
}
});
PHP
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('my#emailaddress.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mygmailusername#gmail.com";
$mail->Password = "passwordform";
$mail->setFrom('mygmailusername#gmail.com', 'Contact Form');
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
You need to initialize $scope.formData = {} so that it can hold the values you are expecting. Right now, its trying to bind values to a scope variable that is undefined.
Edit - It looks like you have no ng-click handler in your button to register the click to the submit. Please add this to your button. Additionally, $valid only works if your input values are enclosed in a .
template.html
<form name="myForm">
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default"
ng-disabled="myForm.$invalid || submitButtonDisabled == true"
ng-click=submit(formData)>Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
What this is doing is its registering the $scope.submit the button, and in the HTML you're passing in formData as a parameter. The now has a name and its required values are checked in ng-disabled of the button which refers to the same name and disables if the I've cleaned up your app.js so that you're getting the params correctly.
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage = '';
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(contactform), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
}
});

Login change in to signup

I have created a HTML5 registration form,is it possible for it to check the email address(inserted first) if it's already used to ask only for password(login) and if it's not to insert other fields needed for signup? using php,js or others.
<form id="signin_student" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
<input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
<input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
<label>Kelas</label>
<select name="class_id" class="input-block-level span5">
<option>Pilih Kelas</option>
<?php
$query = mysql_query("select * from class order by class_name ")or die(mysql_error());
while($row = mysql_fetch_array($query)){
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
?>
</select>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
<button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#signin_student").submit(function(e){
e.preventDefault();
var password = jQuery('#password').val();
var cpassword = jQuery('#cpassword').val();
if (password == cpassword){
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "student_signup.php",
data: formData,
success: function(html){
if(html=='true')
{
var delay = 2000;
setTimeout(function(){ window.location = 'siswa/index.php' }, delay);
}else if(html=='false'){
{ header: 'Data in DB is Not Found' });
}
}
});
}else
{
$.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
}
});
});
</script>
and file signup.php
<?php
mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$class_id = $_POST['class_id'];
$query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
$row = mysql_fetch_array($query);
$id = $row['student_id'];
$count = mysql_num_rows($query);
if ($count > 0){
mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
$_SESSION['id']=$id;
echo 'true';
}else{
echo 'false';
}
?>
Firstly, you could use this code to check when the user stops typing:
Run javascript function when user finishes typing instead of on key up?
Once that is finished, this SQL code may work to check if the email already exists:
SELECT EXISTS(SELECT email FROM email_table)
Then you can simply use a conditional statement to print whether the email exists.

PHP mail function has stopped working

I have created a contact form that sends an email to the website administrator and to the person who filled out the contact form. It was working fine and I have just come back to it to do some more testing and it has stopped sending. To my knowledge I've not changed any of the code. I can't figure out what is wrong with it. Can someone help? Below is the code for the three files I'm using.
This is the contact form file:
<div id="contact-form" class="contact-form">
<div class="rounded-box">
<div class="rounded-box-title">
<h3>Ask for a call back</h3>
<img src="<?php echo get_bloginfo('url') ?>/images-default/br_next.png"/>
</div><!-- .rounded-box-title -->
<?php
$cf = array();
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
?>
<div id="success" class="success"><?php echo ($cf['success']); ?></div>
<script>
$("#success").delay(6000).slideUp();
</script>
<?php
}
?>
<div class="required-text-line">
<span class="required">*</span><span class="required-text">indicates required field</span>
</div>
<form name="contact-form" onsubmit="return validateForm()" action="<?php bloginfo('url'); ?>/wp-content/themes/example/contact-form-send.php" method="POST">
<fieldset>
<label for="fname"><span class="required">*</span>First name:</label></br>
<input type="text" name="fname" id="fname" onblur="return validateFirstName()" value="" />
<span class="error" id="fnameError" style="display: none;"></span>
<script>
$("#fname").blur(function(){
$("#fnameError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="lname"><span class="required">*</span>Last name:</label></br>
<input type="text" name="lname" id="lname" onblur="return validateLastName()" value="" />
<span class="error" id="lnameError" style="display: none;"></span>
<script>
$("#lname").blur(function(){
$("#lnameError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="email"><span class="required">*</span>Email:</label></br>
<input type="text" name="email" id="email" onblur="return validateEmail()" value="" />
<span class="error" id="emailError" style="display: none;"></span>
<script>
$("#email").blur(function(){
$("#emailError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="tel"><span class="required">*</span>Telephone:</label></br>
<input type="text" name="tel" id="tel" onblur="return validateTel()" value="" />
<span class="error" id="telError" style="display: none;"></span>
<script>
$("#tel").blur(function(){
$("#telError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="message"><span class="required">*</span>Message:</label></br>
<textarea name="message" id="message" onblur="return validateMessage()" ></textarea>
<span class="error" id="messageError" style="display: none;"></span>
<script>
$("#message").blur(function(){
$("#messageError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset id="hiddenfield">
<label for="hidden"></label>
<textarea name="hidden" id="hidden" ></textarea>
</fieldset>
<input type="submit" value="Submit" id="submit" />
<script>
$("form").submit(function(){
$(".error").delay(6000).slideUp();
})
</script>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div><!-- .rounded-box -->
</div><!-- .contact-form -->
This is the send PHP file:
<?php
if( isset($_POST) ){
if (empty($_POST ['hidden'])) {
$fname = htmlspecialchars($_POST ['fname']);
$lname = htmlspecialchars($_POST ['lname']);
$email = htmlspecialchars($_POST ['email']);
$tel = htmlspecialchars($_POST ['tel']);
$message = htmlspecialchars($_POST ['message']);
$to = "example#gmail.com";
$subject = "Callback request";
$body = "
<html>
<head>
</head>
<header style='padding:10px'>
<a href='http://example.com'>
<img src='http://example.com/images-default/example-logo.png' alt='example.com'>
</a>
</header>
<body style='border-top:2px solid #91448D;margin-top:15px'>
<p>You have recieved an message through the callback request form on the website.</p>
<p><strong>Name: </strong>{$fname} {$lname} </p>
<p><strong>Email: </strong>{$email} </p>
<p><strong>Telephone: </strong>{$tel} </p>
<p><strong>Message: </strong>{$message}</p>
</body>
</html>
";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: example <info#example.com>' . "\r\n";
$headers .= 'Reply-To: info#example.com' . "\r\n";
mail ( //email to info#example.com
$to,
$subject,
$body,
$headers
);
$subject2 = "Thanks for your enqiry";
$body2 = "
<html>
<head>
</head>
<header style='padding:10px'>
<a href='http://example.com'>
<img src='http://example.com/images-default/example-logo.png' alt='example.com'>
</a>
</header>
<body style='border-top:2px solid #91448D;margin-top:15px'><br/>
<p style='margin-bottom:1em'>Hi {$fname},<br/><br/>
Thanks for enquiring about private maths tuition with <a href='http://example.com'>example.com</a>.<br/><br/>
We'll get back to you within 24 hours for a chat about your child's learning needs.<br/><br/>
Regards,<br/><br/>
<strong>Kathy</strong><br/>
<a href='http://example.com'>example.com</a> founder<br/>
tel: 01582 472060<br/>
email: <a href='mailto:info#example.com'>info#example.com</a></p>
</body>
</html>
";
mail ( //email to enquiror
$email,
$subject2,
$body2,
$headers
);
$success = "Thank you for your enquiry. We'll get back to you within 24 hours.";
$returndata = array (
'success' => $success
);
session_start();
$_SESSION['cf_returndata'] = $returndata;
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
?>
This is the javascript validation file:
function validateFirstName(){
if (
document.getElementById('fname').value == "") {
document.getElementById('fnameError').style.display = "block";
document.getElementById('fnameError').innerHTML = "Please enter your first name";
return false;
}
else {
document.getElementById('fnameError').style.display = "none";
return true;
}
}
function validateLastName(){
if (
document.getElementById('lname').value == "") {
document.getElementById('lnameError').style.display = "block";
document.getElementById('lnameError').innerHTML = "Please enter your last name";
return false;
}
else {
document.getElementById('lnameError').style.display = "none";
return true;
}
}
function validateEmail(){
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(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "none";
return true;
}
else {
if (
document.getElementById('email').value == "") {
document.getElementById('emailError').style.display = "block";
document.getElementById('emailError').innerHTML = "Please enter your email address";
return false;
}
else {
document.getElementById('emailError').style.display = "block";
document.getElementById('emailError').innerHTML = "Please enter a valid email address";
return false;
}
}
}
function validateTel(){
var re = /(((\+44)? ?(\(0\))? ?)|(0))( ?[0-9]{3,4}){3}/;
if (
re.test(document.getElementById('tel').value)){
document.getElementById('telError').style.display = "none";
return true;
}
else {
if (
document.getElementById('tel').value == "") {
document.getElementById('telError').style.display = "block";
document.getElementById('telError').innerHTML = "Please enter your phone number";
return false;
}
else {
document.getElementById('telError').style.display = "block";
document.getElementById('telError').innerHTML = "Please enter a valid phone number";
return false;
}
}
}
function validateMessage(){
if (
document.getElementById('message').value == "") {
document.getElementById('messageError').style.display = "block";
document.getElementById('messageError').innerHTML = "Please enter a message";
return false;
}
else {
document.getElementById('messageError').style.display = "none";
return true;
}
}
function validateForm(){
// Set error catcher
var error = 0;
// Check first name
if(!validateFirstName(document.getElementById('fname').value)){
document.getElementById('fnameError').style.display = "block";
error++;
}
// Check last name
if(!validateLastName(document.getElementById('lname').value)){
document.getElementById('lnameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate phone number
if(!validateTel(document.getElementById('tel').value)){
document.getElementById('telError').style.display = "block";
error++;
}
if(!validateMessage(document.getElementById('message').value)){
document.getElementById('messageError').style.display = "block";
error++;
}
if (
!document.getElementById('hidden').value == "") {
error++;
}
if(error > 0){
return false;
}
}

Contact form with file attachment?

I have a contact form which is a template for pages on wordpress that I use if I need a contact form. All works fine but I want to add the capability of adding a file attachment so when the user fills in their name etc they can upload a photo and that photo will be sent to be me as an attachment.
I have a perfect working contact form and I only want to add that functionality to it. All my current code does all this it sends the name of the person their email address and their message to my email, all I'm missing is the attachment feature. I've been looking at alot of contact forms with this feature but to integrate that feature to my sendmail.php seems very hard as the coding style is completely different. Here is a demo of this in action. demo
This is my php file that has the form in it.
<?php get_header(); ?>
<script type="text/javascript">
$(document).ready(function(){
$('#contact').ajaxForm(function(data) {
if (data==1){
$('#success').fadeIn("slow");
$('#bademail').fadeOut("slow");
$('#badserver').fadeOut("slow");
$('#contact').resetForm();
}
else if (data==2){
$('#badserver').fadeIn("slow");
}
else if (data==3)
{
$('#bademail').fadeIn("slow");
}
});
});
</script>
<!-- begin colLeft -->
<div id="colLeft">
<!-- Begin .postBox -->
<div class="postBox">
<div class="postBoxTop"></div>
<div class="postBoxMid">
<div class="postBoxMidInner first clearfix">
<h1>Contact Us</h1>
<p><?php echo get_option('alltuts_contact_text')?></p>
<p id="success" class="successmsg" style="display:none;">Your email has been sent! Thank you!</p>
<p id="bademail" class="errormsg" style="display:none;">Please enter your name, a message and a valid email address.</p>
<p id="badserver" class="errormsg" style="display:none;">Your email failed. Try again later.</p>
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"></textarea><br />
<input type="submit" id="submitinput" name="submit" class="submit" value="SEND MESSAGE"/>
<input type="hidden" id="receiver" name="receiver" value="<?php echo strhex(get_option('alltuts_contact_email'))?>"/>
</form>
</div>
</div>
<div class="postBoxBottom"></div>
</div>
<!-- End .postBox -->
</div>
<!-- end colleft -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
and here is the file that handles the sending of the mail.
<?php
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
Thanks!
You can read this simple tutorial to know what needs to be done to add file upload support to your current form:
http://www.tizag.com/phpT/fileupload.php
Hope it helps!
EDITED
After the upload process, you can do like this:
if (file_exists($_FILES['uploaded']['tmp_name'])) {
$mail->AddAttachment($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);
}
What this does is to add an attachment to your email by calling the AddAttachment from PHPMailer, and using the file just uploaded from the TMP folder of your server... so no actual storage of the file is necessary.
You can use
http://wordpress.org/plugins/contact-form-7/
It has a option for Upload field as well as all validations, really easy to use.
You just need to enter shortcode and you can use the contact form anywhere you want.