The newsletter subscription form I am working on can be found in the footer at this link.
Currently, when the form is submitted, the error/success message displays on a new page.
Instead I would like for the error/success message to display directly below the form in the footer.
IE. If a user enters the email address [email protected], the text "Success" should display below the input field instead of on a new page.
Help would be greatly appreciated!
Here's what I've got now:
In the Header
<script>
function submitEmail() {
var email = $('#emailText').val();
jQuery.post('/common/php/send_news.php', {
email: email
},function(data){
$('#submissionResponse').html(data);
},html);
}
</script>
FORM
<form method="post">
<fieldset>
<h3></h3>
<input type="text" name="email" maxlength="80" class="input" value="enter your email address..." onfocus="this.className=('input_active')" onblur="this.className=('input')" onclick="this.value='';" />
<input type="button" name="submit" value="" class="subscribe_btn" onmouseover="this.className=('subscribe_btn_over')" onmouseout="this.className=('subscribe_btn')" onclick="submitEmail();" />
<small>*we will not share your email address</small><span class="clear"></span>
</fieldset>
</form>
<div id="submissionResponse"></div>
send_news.php
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[email protected]";
$email_subject = "Newsletter Subscription";
function died($error) {
// your error code can go here
echo "There was an error with your submission";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(
!isset($_POST['email'])) {
died('There was an error with your submission');
}
$email_from = $_POST['email']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Email: ".clean_string($email_from)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thanks for signup up for the Newsletter!
<?php
}
?>
If you wish to do this, you need to use something like an AJAX POST submission, instead of a normal form POST submission. Then you can put the response text anywhere you wish to indicate an error or success condition.