问题
Paul here. I have 2 forms:
a simple 'Signup for news' input for email, and button.
a 'Contact' form with name, email, message. I also have a checkbox to allow sign up to news from this form.
You can see them here on a page called test: http://butterflyepidemic.com/test/
I'm not sure how to set up the logic for the checkbox so that both forms are behaving themselves. If a subscriber uses the signup form, and then wants to send us a message, the contact form simply won't let them progress:
'this email address has already been registered'
. Ideally I'm thinking we should just accept the message regardless of previous registration, or checkbox status. The feedback would always have something positive to say:
'your message has been received'
or
'your message has been received. Your email's already signed up here'
, if not two positive messages:
'your message has been received and you have been signed up'
I'm new to responsive forms. I initially based my development on this tutorial:
http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/
which uses JS, jQuery, PHP, MySQL, JSON. But now I've a 2nd form with more stuff. I was able to get both forms to check both tables for both fields successfully, but now it's feedback logic is wrong. (edit: I mean the PHP for 'contact' form)
HTML for 'signup' form:
<form id="newsletter-signup" action="?action=signup" method="post">
<label for="signup-email">Sign up for news & events:</label>
<input type="email" name="signup-email" id="signup-email" placeholder="Your email here..."></input>
<input type="submit" name="signup-button" id="signup-button" value="Sign Me Up!"></input>
<p id="signup-response"></p>
</form>
and HTML for 'contact' form:
<form id="contact-form" action="?action=contact" method="post">
<legend>Contact us:</legend>
<label for="email">Your email: *</label>
<input type="email" name="contact-email" id="contact-email" placeholder="Your email here..." required></input>
<label for="name">Your Name: *</label>
<input type="name" name="contact-name" id="contact-name" placeholder="Your name here..." required></input>
<label for="message">Your Message: *</label>
<textarea id="contact-textarea" name="contact-textarea" placeholder="Type your message here..." rows = "8" cols = "35" required></textarea>
<label for="checkbox">Subscribe to Newsletter?</label>
<input type="checkbox" name="contact-checkbox" id="contact-checkbox" value="1"></input>
<p id="contact-response"></p>
<input type="submit" name="contact-button" id="contact-button"></input>
</form>
Here's the PHP for the signup form:
<?php
//form 1 - signup
//email signup ajax call
if(isset($_GET['action'])&& $_GET['action'] == 'signup'){
mysql_connect('***','***','***');
mysql_select_db('***');
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = 'error';
$message = 'You did not enter an email address!';
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = 'error';
$message = 'You have entered an invalid email address!';
}
else {
$existingSignup = mysql_query("SELECT * FROM `signups`, `contact` WHERE signup_email_address='$email' OR contact_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){
$status = 'success';
$message = 'you have been signed up!';
}
else {
$status = 'error';
$message = "Oops, there's been a technical error! You have not been signed up.";
}
}
else {
$status = 'error';
$message = 'This email address has already been registered!';
}
}
//return JSON response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
and PHP for the contact form follows:
/*Contact Form*/
//ajax call
if(isset($_GET['action'])&& $_GET['action'] == 'contact'){
mysql_connect('***','***','***');
mysql_select_db('***');
//sanitize data
$email = mysql_real_escape_string($_POST['contact-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = 'error';
$message = 'You did not enter an email address!';
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingContact = mysql_query("SELECT * FROM `signups`, `contact` WHERE signup_email_address='$email' OR contact_email_address='$email'");
if(mysql_num_rows($existingContact) < 1){
//mysql_free_result($existingContact);
//database insert code
if ( isset($_POST['contact-checkbox']) ) {
$checkbox = $_POST['contact-checkbox'];
}
else {
$checkbox = 0;
}
$message = $_POST['contact-textarea'];
$name = $_POST['contact-name'];
$date = date('Y-m-d');
$time = date('H:i:s');
$insertContact = mysql_query("INSERT INTO contact (contact_email_address, contact_date, contact_time, contact_name, contact_message, contact_checkbox) VALUES ('$email','$date','$time','$name','$message','$checkbox')");
if($insertContact){
$status = 'success';
$message = 'your message has been received';
}
else if ($insertContact && $checkbox = $_POST['contact-checkbox']){
$status = 'success';
$message = "your message has been received and you have been signed up";
}
else {
$status = 'error';
$message = "Oops, there's been a technical error!";
}
}
else {
$status = 'error';
$message = 'This email address has already been registered!';
}
}
//return the JSON response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
JS for 'signup' form:
$(document).ready(function(){
$('#newsletter-signup').submit(function(){
//check the form is not currently submitting
if($(this).data('formsstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formsstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server to be validated
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formsstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
})
and finally the JS for the 'contact' form (pretty much the same as for 'signup'):
$(document).ready(function(){
$('#contact-form').submit(function(){
//check the form is not currently submitting
if($(this).data('formsstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#contact-response');
//add status data to form
form.data('formsstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formsstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
})
That's it for the code. I would like to learn how I can set up the logic to give appropriate feedback as in the ideal examples above the code please. I would be happy with any keywords/links/examples of what I may need to research. Thanks, Paul.
回答1:
This works for me:
Step 1: Create a third MySQL table called 'contact_only' in phpmyadmin for people who want to message only (no sign-up)
CREATE TABLE `contact_only` (
`contact_only_id` int(10) NOT NULL AUTO_INCREMENT,
`contact_only_email_address` varchar(250) DEFAULT NULL,
`contact_only_name` varchar(250) DEFAULT NULL,
`contact_only_message` varchar(3000) DEFAULT NULL,
`contact_only_checkbox` tinyint(1) NOT NULL default '0',
`contact_only_date` date DEFAULT NULL,
`contact_only_time` time DEFAULT NULL,
PRIMARY KEY (`contact_only_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Step 2: in the 'contact' form php, use 'if & else if' to give appropriate feedback based on whether user ticked the checkbox or not
if ( isset($_POST['contact-checkbox']) ) {
$existingContact = mysql_query("SELECT * FROM `signups`, `contact` WHERE signup_email_address='$email' OR contact_email_address='$email'");
if(mysql_num_rows($existingContact) < 1){
$checkbox = $_POST['contact-checkbox'];
$message = $_POST['contact-textarea'];
$name = $_POST['contact-name'];
$date = date('Y-m-d');
$time = date('H:i:s');
$insertContact = mysql_query("INSERT INTO contact (contact_email_address, contact_date, contact_time, contact_name, contact_message, contact_checkbox) VALUES ('$email','$date','$time','$name','$message','$checkbox')");
if($insertContact){
$status = 'success';
$message = 'your message has been received and you have been signed up';
}
}
else {
$checkbox = $_POST['contact-checkbox'];
$message = $_POST['contact-textarea'];
$name = $_POST['contact-name'];
$date = date('Y-m-d');
$time = date('H:i:s');
$insertContact = mysql_query("INSERT INTO contact (contact_email_address, contact_date, contact_time, contact_name, contact_message, contact_checkbox) VALUES ('$email','$date','$time','$name','$message','$checkbox')");
$status = 'success';
$message = 'Message received. Note - this email address has already been subscribed!';
}
}
else if (isset($_POST['contact-checkbox']) == false){
$checkbox = 0;
$message = $_POST['contact-textarea'];
$name = $_POST['contact-name'];
$date = date('Y-m-d');
$time = date('H:i:s');
$insertContactOnly = mysql_query("INSERT INTO contact_only (contact_only_email_address, contact_only_date, contact_only_time, contact_only_name, contact_only_message, contact_only_checkbox) VALUES ('$email','$date','$time','$name','$message','$checkbox')");
if ($insertContactOnly) {
$status = 'success';
$message = 'your message has been received';
}
}
else {
$status = 'error';
$message = "Oops, there's been a technical error!";
}
I am happy with this way because it generally gives more positive than negative feedback, and is always appropriate. Here is the link to this solution:
http://butterflyepidemic.com/test/
If you know how to make it faster or more efficient, please let me know! Thanks, Paul
来源:https://stackoverflow.com/questions/21606470/php-logic-for-a-checkbox-where-i-have-2-forms-and-2-mysql-tables