error on contact form submit via jquery ajax - php

Based on this question i had to rewrite my contact form script.
The goal is to to have a send button labeled send. After clickick it should show sending till the php script is done. When its done it should show sent.
Thats my simple form:
<form id="contactForm" action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="Name" required><br />
<input type="text" id="email" name="email" placeholder="Mail" required><br />
<textarea name="message" id="message" placeholder="Nachricht" required></textarea><br />
<button name="submit" type="submit" id="submit">send</button>
</form>
Here is the jquery script for the label changing and the ajax submit.
<script>
$( init );
function init() {
$('#contactForm').submit( submitForm );
}
function submitForm() {
var contactForm = $(this);
if ( !$('#name').val() || !$('#email').val() || !$('#message').val() ) {
$('#submit').html('error');
} else {
$('#submit').html('sending');
$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
$('#submit').HTML = ('sent');
} else {
$('#submit').html('error');
}
}
</script>
the mail.php:
<?php
define( "RECIPIENT_NAME", "John Doe" );
define( "RECIPIENT_EMAIL", "john#doe.com" );
define( "EMAIL_SUBJECT", "Subject" );
$success = false;
$name = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "Von: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
//add html for javascript off user
}
?>
Its submits correct and i get the mail but i doesnt change the label to sent.Its stuck at sending.
Any idea or suggestions whats wrong with my code?
best regards
dennym

The error is on this line:
$('#submit').HTML = ('sent');
Change that to:
$('#submit').html('sent');

$('#submit').HTML = ('sent');
should be
$('#submit').html('sent');
like you have everywhere else.

You have to change
$('#submit').HTML = ('sent');
to:
$('#submit').html('sent');
in your function submitFinished();

Related

My form on wordpress page doesn't execute

I have a page made on wordpress with edited by me custom theme.
I've tried to make my own form using ajax without any plugin.
The problem is that I don't have any errors etc. and form still doesn't do anything (just reloads page). I did everything like on tutorial page and still don't know what to do. I figured out that php code doesn't execute. As you can see there are input conditions that doesn't execute :/
This is what i have done so far:
html:
<section id="contact_content">
<form name="contact_me" action="" method="post">
<?php if( get_field('contact_header') ): ?>
<div id="contact_header"><?php the_field('contact_header'); ?></div>
<?php endif; ?>
<input type="text" name="form_name" placeholder="<?php the_field('contact_name'); ?>" id="contact_name"> <br />
<input type="number" name="form_phone_number" placeholder="<?php the_field('contact_phone'); ?>" id="contact_phone"> <br />
<input type="email" name="form_email" placeholder="<?php the_field('contact_mail'); ?>" id="contact_mail"> <br />
<input type="text" name="form_comment" placeholder="<?php the_field('contact_message'); ?>" id="contact_message" style="height: 190px;"><br />
<input type="hidden" name="action" value="send_form" style="display: none; visibility: hidden; opacity: 0;">
<button type="submit" id="contact_button">wyślij</button>
</form>
</section>
function.php
function javascript_variables(){ ?>
<script type="text/javascript">
let ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
let ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>';
//form AJAX validation
$( 'form[name="contact_me"]' ).on( 'submit', function() {
let form_data = $( this ).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_nonce } );
$.ajax({
url : ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log( response );
},
fail : function( err ) {
console.log( "Błąd: " + err );
}
});
return false;
});
</script><?php
}
add_action ( 'wp_head', 'javascript_variables' );
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
function send_form(){
check_ajax_referer( 'secure-nonce-name', 'security' );
if ( empty( $_POST["form_name"] ) ) {
echo "Wprowadź imię i nazwisko.";
wp_die();
}
if ( ! filter_var( $_POST["form_email"], FILTER_VALIDATE_EMAIL ) ) {
echo "Wprowadź poprawny adres e-mail.";
wp_die();
}
if ( empty( $_POST["form_comment"] ) ) {
echo "Wprowadź wiadomość.";
wp_die();
}
if ( empty($_POST["form_phone_number"] ) ) {
echo 'Wprowadź numer telefonu';
wp_die();
}
$to = 'dawidt9882#gmail.com';
$subject = 'Now message from a client!';
$body = 'From: ' . $_POST['form_name'] . '\n';
$body .= 'Number: ' . $_POST['form_phone_number'] . '\n';
$body .= 'Email: ' . $_POST['form_email'] . '\n';
$body .= 'Message: ' . $_POST['form_comment'] . '\n';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
echo 'Wiadomość została wysłana! ;p';
wp_die();
}
Any ideas? :c
Try this:
$( 'form[name="contact_me"]' ).on( 'submit', function(ev) {
ev.preventDefault();
let form_data = $( this ).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_nonce, "action" : "send_form" } );
$.ajax({
url : ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log( response );
},
fail : function( err ) {
console.log( "Błąd: " + err );
}
});
return false;
});
So now js looks like this:
let ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
let ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>';
//form AJAX validation
$( '#contact_button' ).on( 'click', function(ev) {
ev.preventDefault();
let form_data = $( this ).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_nonce, "action" : "send_form" } );
$.ajax({
url : ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log( response );
},
fail : function( err ) {
console.log( "Błąd: " + err );
}
});
return false;
});
</script><?php
And it still does nothing. :/ If i made a mistake please dissuade me of any notion.

How to make PHP Contact form collect all selected checkboxes

This started off as a pre-built contact form that came bundled in an HTML template. All of the textbox field work perfectly fine when submitting the from. However I need some help with a checkbox section I added myself. I've been trying to do some research but can't get the script to include all the selected checkboxes in the e-mail.
Here's my working html:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="include/sendemail.php" method="post">
<div class="form-process"></div>
<div class="col_half">
<label for="template-contactform-name">Name <small>*</small></label>
<input type="text" id="template-contactform-name" name="template-contactform-name" value="" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="template-contactform-email">Email <small>*</small></label>
<input type="email" id="template-contactform-email" name="template-contactform-email" value="" class="required email sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_half">
<label for="template-contactform-phone">Phone <small>*</small></label>
<input type="text" id="template-contactform-phone" name="template-contactform-phone" value="" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="template-contactform-budget">Budget</label>
<input type="text" id="template-contactform-budget" name="template-contactform-budget" value="" class="sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_full">
<label for="template-contactform-services[]">Services Required: </label>
<input name="template-contactform-services[]" type="checkbox" value="Web-Design" />Web Design
<input name="template-contactform-services[]" type="checkbox" value="E-Commerce" />E-Commerce
<input name="template-contactform-services[]" type="checkbox" value="User-Experience" />User Experience
<input name="template-contactform-services[]" type="checkbox" value="Branding" />Branding
<input name="template-contactform-services[]" type="checkbox" value="Mobile-Design" />Mobile Design
<input name="template-contactform-services[]" type="checkbox" value="Search-Marketing" />Search Marketing
</div>
<div class="col_full">
<label for="template-contactform-message">Deliverables & Goals <small>*</small></label>
<textarea class="required sm-form-control" id="template-contactform-message" name="template-contactform-message" rows="4" cols="30" placeholder="List the specific deliverables, services, and goals required..."></textarea>
</div>
<div class="col_full">
<label for="template-contactform-missing">Anything Missing?</label>
<textarea class="sm-form-control" id="template-contactform-missing" name="template-contactform-missing" rows="4" cols="30" placeholder="Is there anything else you think we should know?"></textarea>
</div>
<div class="col_full hidden">
<input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
</div>
<div class="col_full">
<!--<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="your-recaptcha-site-key"></div>-->
</div>
<div class="col_full">
<button class="button button-3d nomargin" type="submit" id="template-contactform-submit" name="template-contactform-submit" value="submit">Send Message</button>
</div>
</form>
and here's my php:
<?php
require_once('phpmailer/PHPMailerAutoload.php');
$toemails = array();
$toemails[] = array(
'email' => 'info#mydomain.com', // Your Email Address
'name' => 'Your Name' // Your Name
);
// Form Processing Messages
$message_success = 'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.';
// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = 'your-recaptcha-secret-key'; // Your reCaptcha Secret
$mail = new PHPMailer();
// If you intend you use SMTP, add your SMTP Code after this Line
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['template-contactform-email'] != '' ) {
$name = isset( $_POST['template-contactform-name'] ) ? $_POST['template-contactform-name'] : '';
$email = isset( $_POST['template-contactform-email'] ) ? $_POST['template-contactform-email'] : '';
$phone = isset( $_POST['template-contactform-phone'] ) ? $_POST['template-contactform-phone'] : '';
$budget = isset( $_POST['template-contactform-budget'] ) ? $_POST['template-contactform-budget'] : '';
$service = isset( $_POST['template-contactform-services'] ) ? $_POST['template-contactform-services'] : '';
$message = isset( $_POST['template-contactform-message'] ) ? $_POST['template-contactform-message'] : '';
$missing = isset( $_POST['template-contactform-missing'] ) ? $_POST['template-contactform-missing'] : '';
$subject = isset($subject) ? $subject : 'New Message From Contact Form';
$botcheck = $_POST['template-contactform-botcheck'];
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
foreach( $toemails as $toemail ) {
$mail->AddAddress( $toemail['email'] , $toemail['name'] );
}
$mail->Subject = $subject;
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$phone = isset($phone) ? "Phone: $phone<br><br>" : '';
$budget = isset($budget) ? "Budget: $budget<br><br>" : '';
$service = isset($service) ? "Services Required: $service<br><br>" : '';
$message = isset($message) ? "Deliverables & Goals: $message<br><br>" : '';
$missing = isset($missing) ? "Anything Missing: $missing<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = "$name $email $phone $budget $service $message $missing $referrer";
// Runs only when File Field is present in the Contact Form
if ( isset( $_FILES['template-contactform-file'] ) && $_FILES['template-contactform-file']['error'] == UPLOAD_ERR_OK ) {
$mail->IsHTML(true);
$mail->AddAttachment( $_FILES['template-contactform-file']['tmp_name'], $_FILES['template-contactform-file']['name'] );
}
// Runs only when reCaptcha is present in the Contact Form
if( isset( $_POST['g-recaptcha-response'] ) ) {
$recaptcha_response = $_POST['g-recaptcha-response'];
$response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response );
$g_response = json_decode( $response );
if ( $g_response->success !== true ) {
echo '{ "alert": "error", "message": "Captcha not Validated! Please Try Again." }';
die;
}
}
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
echo '{ "alert": "success", "message": "' . $message_success . '" }';
else:
echo '{ "alert": "error", "message": "Email <strong>could not</strong> be sent due to some Unexpected Error. Please Try Again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '" }';
endif;
} else {
echo '{ "alert": "error", "message": "Bot <strong>Detected</strong>.! Clean yourself Botster.!" }';
}
} else {
echo '{ "alert": "error", "message": "Please <strong>Fill up</strong> all the Fields and Try Again." }';
}
} else {
echo '{ "alert": "error", "message": "An <strong>unexpected error</strong> occured. Please Try Again later." }';
}
?>
Thanks in advance
You have to give different name attributes to the <input type="checkbox" /> tag. Then you can check whether a checkbox is checked with the isset() function.

PHP to post to different user dependent on form name

Trying to work out the best way to get the PHP below to post to a different user email address dependent on the form name it is coming from.
Eg. this form is name="engineering-australia" and I have others with different names. I want this one to go to user1#domain.com and an other to go to user2#domain.com and so on.
My question is, what would be the best way to do this, I don't want to use javascript- I was thinking some kind of if statement? But wouldn't the form name need to be pulled in somehow?
Also worth mentioning the forms are identical apart from the form name, I didn't want to just create a different PHP script for each form.
HTML
<form class="form-contact" name="engineering-australia">
<fieldset>
<input id="form-name" name="name" type="text" placeholder="Your Name" />
<input id="form-email" name="email" type="text" placeholder="Your Email" />
</fieldset>
<textarea id="form-msg" name="message" rows="10" placeholder="Your Message" ></textarea>
<input type="submit" name="submit" class="button button-small" value="Send Message" />
</form>
PHP
<?php
define('kOptional', true);
define('kMandatory', false);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('track_errors', true);
function DoStripSlashes($fieldValue) {
// temporary fix for PHP6 compatibility - magic quotes deprecated in PHP6
if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
if (is_array($fieldValue) ) {
return array_map('DoStripSlashes', $fieldValue);
} else {
return trim(stripslashes($fieldValue));
}
} else {
return $fieldValue;
}
}
function FilterCChars($theString) {
return preg_replace('/[\x00-\x1F]/', '', $theString);
}
function CheckEmail($email, $optional) {
if ( (strlen($email) == 0) && ($optional === kOptional) ) {
return true;
} elseif ( preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $email) == 1 ) {
return true;
} else {
return false;
}
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
$FTGname = DoStripSlashes( $_POST['name'] );
$FTGemail = DoStripSlashes( $_POST['email'] );
$FTGmessage = DoStripSlashes( $_POST['message'] );
$FTGsubmit = DoStripSlashes( $_POST['submit'] );
$validationFailed = false;
# Fields Validations
if (!CheckEmail($FTGemail, kMandatory)) {
$FTGErrorMessage['email'] = 'ERROR MESSAGE';
$validationFailed = true;
}
# Redirect user to error message
if ($validationFailed === true) {
header("Location: index.php?success=2");
}
if ( $validationFailed === false ) {
# Email to Form Owner
$emailSubject = FilterCChars("Website Enquiry");
$emailBody = chunk_split( base64_encode( "<html>\n"
. "<head>\n"
. "<title></title>\n"
. "</head>\n"
. "<body>\n"
. "Name : $FTGname<br />\n"
. "Email : $FTGemail<br />\n"
. "Message : " . nl2br( $FTGmessage ) . "\n"
. "</body>\n"
. "</html>" ) )
. "\n";
$emailTo = 'User <user1#domain.com>';
$emailFrom = FilterCChars("$FTGemail");
$emailHeader = "From: $emailFrom\n"
. "MIME-Version: 1.0\n"
. "Content-Type: text/html; charset=\"UTF-8\"\n"
. "Content-Transfer-Encoding: base64\n"
. "\n";
mail($emailTo, $emailSubject, $emailBody, $emailHeader);
# Redirect user to success message
header("Location: index.php?success=1");
}
?>
You're not going to get the form name in PHP. Try using a hidden input in each form:
<input name="form" type="hidden" value="engineering-australia" />
Then check $_POST['form'] in PHP.
switch($_POST['form']) {
case 'engineering-australia':
$email = 'user1#domain.com';
break;
case 'something-else':
$email = 'user2#domain.com';
break;
}
Change:
<form class="form-contact" name="engineering-australia">
<fieldset>
To:
<form class="form-contact">
<input type="hidden" name="post-to" value="engineering-australia" />
<fieldset>
Now you can check who you want to send the email to by simply requesting $_POST['post-to'] on the submit action page.

AJAX/JQuery error when trying to send data

Not sure why, but I added an "error" clause to make sure the AJAX was failing... it is. It works correctly up to the AJAX portion, it's just not sending the data, no idea why.
<script type="text/javascript">
<!--
$(document).ready(function() {
$("#login").click(function() {
document.getElementById("result").innerHTML = 'Validating credentials...';
var un = $("#un").val();
var pw = $("#pw").val();
if ( un == "" )
{
document.getElementById("un_error").style.visibility = 'visible';
$("#un").focus();
}
if ( pw == "" )
{
document.getElementById("pw_error").style.visibility = 'visible';
$("#pw").focus();
}
$.ajax({
type: 'POST',
url: 'login-parse.php',
data: { un: un, pw: md5(pw) },
success: function(msg) {
document.getElementById("result").innerHTML = msg;
},
error: function(xhr, status) { alert(status); }
});
});
});
//-->
</script>
That's the JS code.
This is the HTML:
<div id="content">
<div id="result" class="result"></div>
<h2>Login To Your Account</h2>
<div class="text">
<fieldset>
<fieldset>
<legend>Username</legend>
<input type="text" id="un" value="" size="20" /><span class="error" id="un_error">*</span>
</fieldset>
<fieldset>
<legend>Password</legend>
<input type="password" id="pw" value="" size="30" /> <span class="error" id="pw_error">*</span>
</fieldset>
<input type="button" id="login" value="Login" />
</fieldset>
</div>
</div>
<?php
// Login Parser
require 'inc.common.php';
if (! isset ( $_POST['un'], $_POST['pw']) )
{
echo '<blockquote>Invalid username/password combination.</blockquote>' . "\n";
} else {
$un = $_POST['un'];
$pw = md5($_POST['pw']);
$check = $sql->result ( $sql->query ( 'SELECT COUNT(*) FROM `users` WHERE `user_name` = \'' . $sql->escape($un) . '\' AND `user_password` = \'' . $sql->escape($pw) . '\'' ) );
$errors = array();
if (! strlen ( $un ) )
$errors[] = 'Please enter a valid username.';
if (! strlen ( $pw ) )
$errors[] = 'Please enter a valid password.';
if ( $check == 0 )
$errors[] = 'Invalid username/password combination.';
if ( count ( $errors ) > 0 )
{
echo '<blockquote>' . "\n",
' The following errors occurred with your login:' . "\n",
' <ul>' . "\n";
foreach ( $errors as $enum => $error )
{
echo ' <li><strong>(#' . ($enum+1) . '):</strong> ' . $error . '</li>' . "\n";
}
echo ' </ul>' . "\n",
'</blockquote>' . "\n";
} else {
setcookie ( 'ajax_un', $un, time()+60*3600 );
setcookie ( 'ajax_pw', $pw, time()+60*3600 );
echo '<blockquote>' . "\n",
' <p><strong>Success!</strong></p>' . "\n",
' <p>You have successfully been logged in as <strong>' . $un . '</strong>.</p>' . "\n",
' <p>You may now return to the index page.</p>' . "\n",
'</blockquote>' . "\n";
}
}
?>
From the message "500 - Internal Server Error" in Firebug console, and the code you have posted, it seems that there is some problem in database operation.
So try to store your query a variable. Echo it and try executing same in phpMyadmin or other equivalent client you are using to access database.
If possible also post the result.

Ajax/PHP contact form not able to send mail

The funny thing is it did work for one evening. I contacted my host, and they are saying there's no reason it should not be working. I have also attempted to test it in Firebug, but it seemed to be sending. And I specifically put the email address (hosted in my domain) on my email safe list, so that is not the culprit either.
Would anyone here take a look at it for me? I'd be so grateful.
In the header I have:
<script type="text/javascript">
$(document).ready(function () {
var options = {
target: '#alert'
};
$('#contactForm').ajaxForm(options);
});
$.fn.clearForm = function () {
return this.each(function () {
var type = this.type,
tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
Here is the actual form:
<form id="contactForm" method="post" action="sendmail.php">
<fieldset>
<p>Email Me</p>
<div id="fieldset_container">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" /><br /><br />
<label for="email">Email:</label>
<input type="text" name="email" id="email" /><br /><br />
<span style="display:none;">
<label for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" />
</span><br /><br />
<label for="message">Comments & Inquiries:</label>
<textarea name="message" id="message" cols="" rows=""></textarea><br/>
</div>
<div id="submit_button">
<input type="submit" name="submit" id="submit" value="Send It" />
</div>
</fieldset>
</form>
<div class="message"><div id="alert"></div></div>
Here is the code from my validating page, sendmail.php:
<?php
// Who you want to recieve the emails from the form. (Hint: generally you.)
$sendto = 'my#emailaddress.com';
// The subject you'll see in your inbox
$subject = 'SH Contact Form';
// Message for the user when he/she doesn't fill in the form correctly.
$errormessage = 'There seems to have been a problem. May I suggest...';
// Message for the user when he/she fills in the form correctly.
$thanks = "Thanks for the email!";
// Message for the bot when it fills in in at all.
$honeypot = "You filled in the honeypot! If you're human, try again!";
// Various messages displayed when the fields are empty.
$emptyname = 'Entering your name?';
$emptyemail = 'Entering your email address?';
$emptymessage = 'Entering a message?';
// Various messages displayed when the fields are incorrectly formatted.
$alertname = 'Entering your name using only the standard alphabet?';
$alertemail = 'Entering your email in this format: <i>name#example.com</i>?';
$alertmessage = "Making sure you aren't using any parenthesis or other escaping characters in the message? Most URLS are fine though!";
//Setting used variables.
$alert = '';
$pass = 0;
// Sanitizing the data, kind of done via error messages first. Twice is better! ;-)
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
//The first if for honeypot.
if ( empty($_REQUEST['last']) ) {
// A bunch of if's for all the fields and the error messages.
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
} elseif ( ereg( "[][{}()*+?.\\^$|]", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
} elseif ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
} elseif ( ereg( "[][{}()*+?\\^$|]", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
//If the user err'd, print the error messages.
if ( $pass==1 ) {
//This first line is for ajax/javascript, comment it or delete it if this isn't your cup o' tea.
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo "<b>" . $errormessage . "</b>";
echo "<ul>";
echo $alert;
echo "</ul>";
// If the user didn't err and there is in fact a message, time to email it.
} elseif (isset($_REQUEST['message'])) {
//Construct the message.
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
//Mail the message - for production
mail($sendto, $subject, $message, $header, "-fstephanie#stephaniehenderson.com");
//This is for javascript,
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\").animate({opacity: 1.0}, 4000).hide(\"slow\"); $(':input').clearForm() </script>";
echo $thanks;
die();
//Echo the email message - for development
echo "<br/><br/>" . $message;
}
//If honeypot is filled, trigger the message that bot likely won't see.
} else {
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo $honeypot;
}
?>
If the message is echoing then it's not a problem with your javascript or html. I would suggest making a fresh PHP file with only the 1 line that attempts to send mail:
mail('youremailaddress#example.com', 'My Subject', 'This is a message');
Hardcode everything. If that works, then you know that it's probably not a problem with your host, and you need to examine that line and the variables to are passing to mail()

Categories