I've been trying to figure out why my phone string is the only one not being printed in the received email from the contact form.
I have the following:
HTML:
<input
id="phone"
type="text"
name="phone"
placeholder="Telefone"
/>
PHP:
include_once (dirname(dirname(__FILE__)) . '/config.php');
$response = null;
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case "SendMessage": {
if (isset($_POST["email"]) && !empty($_POST["email"])) {
$message = $_POST["message"];
$message .= "<br/><br/>";
$message .= "phone:".$_POST["phone"];
$response = (SendEmail($message, $_POST["subject"], $_POST["name"], $_POST["email"], $email)) ? 'Mensagem Enviada!!' : "Sending Message Failed";
} else {
$response = "Sending Message Failed";
}
}
break;
default: {
$response = "Invalid action is set! Action is: " . $action;
}
}
}
JS:
function SendMail() {
$('.contact-form [type="submit"]').on('click', function () {
var emailVal = $('#contact-email').val();
if (isValidEmailAddress(emailVal)) {
var params = {
'action': 'SendMessage',
'name': $('#name').val(),
'email': $('#contact-email').val(),
'phone': $('#phone').val(),
'subject': $('#subject').val(),
'message': $('#message').val()
};
As i said, everything else is being received on our email, but the phone string.
What am i doing wrong?
Related
I have a contact form that is performing validation on the back end, what I want to check for is if the user has successfully completed the captcha or not and if not print an error message.
Currently, I am getting an error message:
Notice: Undefined index: g-recaptcha-response in /var/www/html/mangoForm.php on line 99
So it isn't printing the error message that is in the JSON:
{"success":false,"errors":{"captcha":"ReCaptcha is required."}}
Line 99:
$captcha = checkCaptcha($formData['g-recaptcha-response']);
Code Block in Question:
if (!empty($validationMSG)) {
return $validationMSG;
}
else {
$captcha = checkCaptcha($formData['g-recaptcha-response']);
if(!$captcha['isSuccess']){
$validationMSG['captcha'] = 'ReCaptcha is required.';
return $validationMSG;
}
//End of Validation Function
}
}
Full Code:
<?php
//show errors - enable this
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
//Var Dump (Debugging)
//var_dump($_POST);
//Load Required Components
require_once 'src/recaptcha_autoload.php';
require_once "functions.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
function validate($formData)
{
// Initiate Array
$validationMSG = array(); // array to hold validation errors
$pname_exp = '/^[a-zA-Z0-9\_]{2,20}/';
if (!isset($formData['firstName'])) {
$validationMSG['firstName'] = 'First Name is required.';
}elseif (!preg_match($pname_exp, $formData['firstName'])){
$validationMSG['firstName'] = 'First Name is not valid.';
}
// Validate lastName
if (!isset($formData['lastName'])) {
$validationMSG['lastName'] = 'Last Name is required.';
}
// Check RegEx for Last Name
elseif (!preg_match($pname_exp, $formData['lastName'])) {
$validationMSG['lastName'] = 'Last Name is not valid.';
}
// Validate companyName
if (!isset($formData['companyName'])) {
$validationMSG['companyName'] = 'Company Name is required.';
}
// Validate companyAddress
if (!isset($formData['companyAddress'])) {
$validationMSG['companyAddress'] = 'Company Address is required.';
}
// Validate state
if (!isset($formData['state'])) {
$validationMSG['state'] = 'State is required.';
}
// Validate city
if (!isset($formData['city'])) {
$validationMSG['city'] = 'City is required.';
}
// Validate Zipcode - If Field is Empty
if (!isset($formData['zipcode'])) {
$validationMSG['zipcode'] = 'Zipcode is required.';
}
// Validate emailAddress
if (!isset($formData['emailAddress'])) {
$validationMSG['emailAddress'] = 'Email Address is required.';
}
// Check if emailAddress is a valid email address
elseif (!filter_var($formData['emailAddress'], FILTER_VALIDATE_EMAIL)) {
$validationMSG['emailAddress'] = 'Email address is not valid.';
}
//Validate phoneNumber
if (!isset($formData['phoneNumber'])) {
$validationMSG['phoneNumber'] = 'Phone Number is required.';
}
//Validate phoneNumber
elseif (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $formData['phoneNumber'])) {
$validationMSG['phoneNumber'] = 'Must be a valid phone number.';
}
var_dump($formData);
// Validate message
if (!isset($formData['message'])) {
$validationMSG['message'] = 'Message is required.';
}
if (!empty($validationMSG)) {
return $validationMSG;
}
else {
$captcha = checkCaptcha($formData['g-recaptcha-response']);
if(!$captcha['isSuccess']){
$validationMSG['captcha'] = 'ReCaptcha is required.';
return $validationMSG;
}
//End of Validation Function
}
}
function checkCaptcha($g_recaptcha_response)
{
$recaptcha_secret_key = 'REDACTED';
$recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_secret_key);
$resp = $recaptcha->verify($g_recaptcha_response, $_SERVER['REMOTE_ADDR']);
return [
'isSuccess' => $resp->isSuccess(),
'errorCodes' => $resp->getErrorCodes(),
];
}
function sendMail($formData)
{
$mail = new PHPMailer(true); // Passing `true` enables exceptions
// Server settings
//$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.server.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#server.com'; // SMTP username
$mail->Password = 'REDACTED'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
// Recipients
$mail->setFrom('user#server.com', 'Mailer');
$mail->addAddress('user#server.com', 'Joe User'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Message from Contact Form';
// prepare email body
$body_message = "";
$body_message.= "Sender IP: " . get_client_ip() . "<br />";
// #todo: make the other rows the same way, i.e. $formData['key'];
$body_message.= "First Name: " . $formData['firstName'] . "<br />";
$body_message.= "Last Name: " . $formData['lastName'] . "<br />";
$body_message.= "Company Name: " . $formData['companyName'] . "<br />";
$body_message.= "Company Address: " . $formData['companyAddress'] . "<br />";
$body_message.= "City: " . $formData['city'] . "<br />";
$body_message.= "State: " . $formData['state'] . "<br />";
$body_message.= "Sender email: " . $formData['emailAddress'] . "<br />";
$body_message.= "Sender Phone: " . $formData['phoneNumber'] . "<br />";
$body_message.= "\n\n" . $formData['message'];
$mail->Body = $body_message;
$mail->send();
}
/////////////////////////////////////////////////
// process
//this will be our whole response (jsoned later)
$response = [
//we'll change these later, possibly:
'success' => false,
'errors' => [],
// 'message' => 'There has been an issue sending your message!!!!',//could be an "OK" error message as well, depends on the 'success' key.
];
// Copy $_POST to $formData
//$formData = $_POST;
//$formData = json_decode($_POST, true);
$formData = json_decode(file_get_contents("php://input"), true);
//validate
$errors = validate($formData);
if(!empty($errors)){
$response['success'] = false;
$response['errors'] = $errors;
}else {//it's ok
//send it
try{
sendMail($formData);
//Print Success Message
$response['success'] = true;
$response['message'] = 'Message was Sent!';
}
catch(Exception $e) {
// Print phpMailer Error Message
$response['success'] = false;
$response['message'] = 'There has been an issue sending your message';
}
}
echo json_encode($response);
exit;
How I can achieve where the PHP script checks for a successful response from Google ReCaptcha and either permits the script to go on further in the event of a success or print an error message?
EDITED JS:
document.querySelector("#form").addEventListener("submit", function(e){
//create variable for contact form url
var formURL = 'mangoForm.php';
//prevent default submission
event.preventDefault();
//define form fields
var mangoForm = {
'firstName' : document.querySelector('input[name=firstName]').value,
'lastName' : document.querySelector('input[name=lastName]').value,
'companyName' : document.querySelector('input[name=companyName]').value,
'companyAddress' : document.querySelector('input[name=companyAddress]').value,
'city' : document.querySelector('input[name=city]').value,
'state' : document.querySelector('select[name=state]').value,
'zipcode' : document.querySelector('input[name=zipcode]').value,
'emailAddress' : document.querySelector('input[name=emailAddress]').value,
'phoneNumber' : document.querySelector('input[name=phoneNumber]').value,
'message' : document.querySelector('input[name=message]').value,
}
//define request variable
var formRequest = new Request(formURL, {
method: 'POST',
body: JSON.stringify(mangoForm),
headers: {
"content-type":"application/json; charset=utf-8"
}
});
//fetch
fetch(formRequest)
//console.log(formRequest)
.then(function(formResponse) {
return formResponse.json();
})
.then(function(data) {
//handle server responses
if ( ! data.success) {
//handle error messages
//handle error message for firstName
//console.log(data);
if (data.errors.firstName && !document.querySelector('#firstName-group .help-block')) {
document.getElementById("firstName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.firstName;
document.getElementById("firstName-group").append(helpBlock);
}
//handle errors for lastName
if (data.errors.lastName && !document.querySelector('#lastName-group .help-block')) {
document.getElementById("lastName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.lastName;
document.getElementById("lastName-group").appendChild(helpBlock);
}
//handle errors for companyName
if (data.errors.companyName && !document.querySelector('#companyName-group .help-block')) {
document.getElementById("companyName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.companyName;
document.getElementById("companyName-group").appendChild(helpBlock);
}
//handle errors for companyAddress
if (data.errors.companyAddress && !document.querySelector('#companyAddress-group .help-block')) {
document.getElementById("companyAddress-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.companyAddress;
document.getElementById("companyAddress-group").appendChild(helpBlock);
}
//handle errors for city
if (data.errors.city && !document.querySelector('#city-group .help-block')) {
document.getElementById("city-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.city;
document.getElementById("city-group").appendChild(helpBlock);
}
//handle errors for state
if (data.errors.state && !document.querySelector('#state-group .help-block')) {
document.getElementById("state-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.state;
document.getElementById("state-group").appendChild(helpBlock);
}
//handle errors for zipcode
if (data.errors.zipcode && !document.querySelector('#zipcode-group .help-block')) {
document.getElementById("zipcode-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.zipcode;
document.getElementById("zipcode-group").appendChild(helpBlock);
}
//handle errors for emailAddress
if (data.errors.emailAddress && !document.querySelector('#emailAddress-group .help-block')) {
document.getElementById("emailAddress-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.emailAddress;
document.getElementById("emailAddress-group").appendChild(helpBlock);
}
//handle errors for phoneNumber
if (data.errors.phoneNumber && !document.querySelector('#phoneNumber-group .help-block')) {
document.getElementById("phoneNumber-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.phoneNumber;
document.getElementById("phoneNumber-group").appendChild(helpBlock);
}
//handle errors for message
if (data.errors.message && !document.querySelector('#message-group .help-block')) {
document.getElementById("message-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.message;
document.getElementById("message-group").appendChild(helpBlock);
}
// handle errors for captcha ---------------
if (data.errors.captcha) {
swal({
title: "Error!",
text: data.errors.captcha,
icon: "error",
});
}
// handle errors for phpmailer ---------------
if (data.message) {
swal({
title: "Error!",
text: data.message,
icon: "error",
});
}
if (data.success) {
swal({
title: "Success!",
text: data.message,
icon: "success",
});
//document.getElementById("form").reset();
}
}
});
})
As mentioned by #marv255 there actually is no captcha data in your request apparently.
So try adding this:
'g-recaptcha-response' : grecaptcha.getResponse()
Just below
'message' : document.query ...
In your js file.
I am using Opencart V2.0.1.1 for one project and i have a custom form in product page(.tpl). I want to send mail to store owner on submit of that form. I am able to process it and receiving the data till model but from model i am not able to send the mail and i am getting below error.
SyntaxError: Unexpected token < OK Notice: Undefined property:
Mail::$ErrorInfo in
/opt/lampp/htdocs/dutees/catalog/model/catalog/product.php on
line 784{"success":"success"}
Below is my code
// CONTROLLER FUNCTION
public function getquote()
{
$data = array(); $json = array();
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
}
if (isset($this->request->post['mobile'])) {
$data['mobile'] = $this->request->post['mobile'];
}
if (isset($this->request->post['address'])) {
$data['address'] = $this->request->post['address'];
}
if (isset($this->request->post['description'])) {
$data['description'] = $this->request->post['description'];
}
if($this->config->get('config_email') != 'null' || $this->config->get('config_email') !='')
$data['store_email'] = $this->config->get('config_email');
if($this->config->get('config_name') != 'null' || $this->config->get('config_name') !='')
$data['store_name'] = $this->config->get('config_name');
$this->load->model('catalog/product');
$gq_status = $this->model_catalog_product->sendQuote($data);
if($gq_status = "success"){
$json['success'] = "success";
}else{
$json['error'] = "Error : We are unable to send your request now, please use contact-us form";
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
// MODEL FUNTION
public function sendQuote($data = array()) {
$status = ""; $name ="";$email ="";$mobile ="";$address ="";$description ="";
if(isset($data['name']))
$name = $data['name'];
else
$name = "Not Available";
if(isset($data['email']))
$email = $data['email'];
else
$email = "Not Available";
if(isset($data['mobile']))
$mobile = $data['mobile'];
else
$mobile = "Not Available";
if(isset($data['address']))
$address = $data['address'];
else
$address = "Not Available";
if(isset($data['description']))
$description = $data['description'];
else
$description = "Not Available";
if(isset($data['store_email']))
$store_email = $data['store_email'];
else
$store_email = "abc#def.net";
if(isset($data['store_name']))
$store_name = $data['store_name'];
else
$store_name = "Enquiry";
$message = '
<html>
<body>
<MY HTML MAIL CONTENT GOES HERE>
</body>
</html>
';
$this->load->mail;
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->hostname = $this->config->get('config_smtp_host');
$mail->username = $this->config->get('config_smtp_username');
$mail->password = $this->config->get('config_smtp_password');
$mail->port = $this->config->get('config_smtp_port');
$mail->timeout = $this->config->get('config_smtp_timeout');
$mail->setTo($store_email);
$mail->setFrom($email);
$mail->setSender($store_name);
$mail->setSubject("Product Get Quote");
//$mail->setText("test message body text");
$mail->setHtml($message);
if(!$mail->send()) {
$status = 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$status = 'success';
}
return $status;
}
// VIEW AJAX
<script>
$('#gq-submit').click(function(){
var name=$('#gq-name').val();
var email=$('#gq-email').val();
var mobile=$('#gq-mobile').val();
var address=$('#gq-address').val();
var description=$('#gq-description').val();
if(name != '' && email != ''&& mobile != '' && description != ''){
$.ajax({
type:'post',
url:'index.php?route=product/product/getquote',
dataType: 'json',
data:'name='+name+'&email='+email+'&mobile='+mobile+'&address='+address+'&description='+description,
beforeSend: function() {
$('#gq-submit').button('loading');
},
complete: function() {
$('#gq-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#gq-showcheck').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});}else{
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + "Please fill all the fields" + '</div>');
}
});
</script>
You can't send mail, maybe the mail settings are incorrect and
the Opencart own Mail class hasn't any ErrorInfo field inside it.
See: system/library/mail.php
First of all set the the correct mail parameters and don't use $mail->ErrorInfo because it doesn't exist. When error occured during sending mail it calls a trigger_error.
I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));
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.
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
Okay so i got this form in my website and when i test it and try to send an email message it says that the message has been sent but i dong get it to my email...
here are the codes:
contact.php:
<?php
function ValidateEmail($email)
{
$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;
}
include 'config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
if(!$name)
{
$error .= '<p>Please enter your name.</p>';
}
if(!$email)
{
$error .= '<p>Please enter an e-mail address.</p>';
}
if($email && !ValidateEmail($email))
{
$error .= '<p>Please enter a valid e-mail address.</p>';
}
if(!$subject || strlen($subject) < 2)
{
$error .= "<p>Please enter the subject.</p>";
}
if(!$message || strlen($message) < 2)
{
$error .= "<p>Please enter your message.</p>";
}
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div id="notification">'.$error.'</div>';
}
}
?>
config.php:
<?php
// Change this to your email account
define("WEBMASTER_EMAIL", 'my mail address');
?>
form.js:
$(document).ready(function(){
$("#contactForm").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
result = '<div id="notification"><p>Your message has been sent. Thank you!</p></div>';
$('#contactForm').each (function(){
this.reset();
});
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
Thanks!!
Change var str = $(this).serialize(); to data: $("#contactForm").serialize(),