Sending an email with ajax and object oriented php best practices - php

I am building a form to send an email and I want to use Object Oriented Php and Ajax.
I was able to build the PHP backend (variable and function) regardless of Ajax, but I have problems in making the Ajax call because I have not yet understood what are the steps to follow.
My problem is that I don't really understand how the ajax URL works (the call the to PHP file). Should I try to target the function (and how can I do) or should I call the page directly, in which I'm gonna create the json function to output a json file to parse with ajax?
Here's my code:
Footer.php and main.js
$('#contact-form').on('submit',function(e) {
e.preventDefault();
$('.output-message').text('Loading...');
const form = $(this);
const post_url = $(this).attr("action");
console.log(post_url);
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
if (result == 'success'){
$('.output-message').text('Message Sent!');
} else {
$('.output-message').text('Error Sending email!');
}
}
});
return false;
});
<form id="contact-form" name="contact-form" action="Contact.php" method="POST" data-parsley-validate="">
<div class="row">
<div class="col-md-6">
<div class="md-form mb-0">
<input type="text" id="name" name="name" class="form-control" required="">
<label for="name" class="">Your name</label>
</div>
</div>
<div class="col-md-6">
<div class="md-form mb-0">
<input type="email" id="email" name="email" class="form-control" required="">
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea" required=""></textarea>
<label for="message">Your message</label>
</div>
</div>
</div>
<div class="text-center text-md-right">
<input type="submit" id="submit" class="btn-primary" name="submit" value="Request Info">
<span class="output-message"></span>
</div>
</form>
And the php Class:
Contact.php
<?php
class Contact {
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
echo '<p class=\'message error\'>';
echo '<font color="black">' . $errors . '</font>';
echo '</p><br />';
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
$sendMail->sendMail();
}
?>
The javascript part doesn't work, and I'm trying to understand this part:
const post_url = $(this).attr("action");
$.ajax({
url: post_url,
Should I create another function in PHP that will output a JSON file that collects all the variables?
My though is that I'm serializing the URL and then I will send it to the PHP file, but I'm not even able to console.log() the result.

Refactor a little bit :
class Contact
{
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
throw new Exception($errors, 400);
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
header('Content-Type: aaplication/json');
try {
$sendMail->sendMail();
echo json_encode(array('success' => 'success'));
} catch (Exception $e) {
header ('HTTP/1.1 400 Bad Request')
$errors = array('error' => $e->getMessage);
echo json_encode($errors);
}
}
I've made it return the string instead of echoing in the class, and I've thrown an exception on an error. Also, since we are sending to JS I made it return JSON.
Lastly, change the JS here:
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
$('.output-message').text('Message Sent!');
}
error: function(result) {
console.log(result);
$('.output-message').text('Error Sending email!');
}
});
JS will check a 200, so know if it is success. Since you now send a 400 on error, the error function will trigger! Give that a try :-)

Related

PHP validation always returns error/false in ajax even the conditions are true

I have only two conditions.
If the yourname is empty return error
If the email is empty returns error
but I get error even if both are not empty.
I could not figure out why.
My Form
<form action="" method="post" name="contact-me" id="profile-update" class="requires-validation">
<div class="d-flex flex-row align-items-center mb-4">
<i class="fas fa-key fa-lg me-3 fa-fw"></i>
<div class="d-flex form-floating mb-0 flex-fill">
<input name="yourname" type="text" class="form-control name" placeholder="Type your name" >
<label for="yourname" class="form-label">Your Name</label>
<div class="yournameerror">Name field is valid!</div>
</div>
</div>
<div class="d-flex flex-row align-items-center mb-4">
<i class="fas fa-key fa-lg me-3 fa-fw"></i>
<div class="d-flex form-floating mb-0 flex-fill">
<input name="email" type="email" class="form-control" placeholder="Type a valid email" >
<label for="email" class="form-label">Your Email</label>
<div class="emailerror">Name field is valid!</div>
</div>
</div>
<div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
<button type="submit" class="btn btn-primary btn-lg" id="submit">Send message!</button>
</div>
<div id="nds_form_feedback"></div>
</form>
Validation function
<?php
function stack_update_validation_func(){
$errors = array();
$response = array();
$yourname=$_POST['yourname'];
$email=$_POST['email'];
if ($_POST['yourname'] == '') {
$errors['yourname'] = "Please enter your name";
}
if ((empty($_POST['email'])) ) {
$errors['email'] = "Please enter your email";
}
$response['errors'] = $errors;
if($errors !== '') {
$response['success'] = false;
$response['message'] = "Fail";
} else {
$reponse['success'] = true;
$response['message'] = "<div class='alert alert-success'>Article added</div>";
}
header("Content-Type: application/json", true);
echo json_encode($response);
wp_die();
}
Getting that JSON response in this Ajax:
Please read the comments as well
<script type="text/javascript">
jQuery(document).on('click', '#submit', function(e){
e.preventDefault();
var data = new FormData();
data.append('action', 'stack_update_validation_func');
jQuery.ajax({
type: 'POST',
url: ajax_url,
data: data,
contentType: false, //because I have a file upload feild as well
processData: false, //because I have a file upload feild as well
headers: {Accept : "application/json;charset=utf-8"},
dataType: 'json',
debug:true,
success: function(response) {
if(response.success) {
jQuery("#nds_form_feedback").html('Sucessfully Sent'); // if the form passes the validation this works fine
}
else {
alert("Not Uploaded"); // shows the popup if there is a validation error
jQuery.each(response.errors, function(key, val) {
console.log(key); // returns the key like this https://prnt.sc/I4R0rNdRIF0o
});
console.log(response); // returns the json response in console
jQuery.each(response.errors, function(key, val) {
jQuery('#profile-update [name="'+key+'"]').parent().find('.'+key+'error').html(val);
});
}
}
});
});
</script>
console.log(response); shows this
but the issue is even yourname and email are filled correctly the error message is shown.
not sure what is wrong. please help.
In your method stack_update_validation_func there is a condition if($errors !== '') {. This condition will always be true because $errors will never be an empty string. It is initialized as empty array. So you should update the condition and your method could look like this:
function stack_update_validation_func()
{
$errors = array();
$response = array();
$yourname = $_POST['yourname'];
$email = $_POST['email'];
if ($_POST['yourname'] == '') {
$errors['yourname'] = "Please enter your name";
}
if (empty($_POST['email'])) {
$errors['email'] = "Please enter your email";
}
$response['errors'] = $errors;
if(!empty($errors)) {
$response['success'] = false;
$response['message'] = "Fail";
} else {
$response['success'] = true;
$response['message'] = "<div class='alert alert-success'>Article added</div>";
}
header("Content-Type: application/json", true);
echo json_encode($response);
wp_die();
}
Update: Here is also the part of the JavaScript, that had to be updated:
// instead of `var data = new FormData();`
var data = new FormData(document.getElementById('profile-update'));

Change the color of messages when submitting a form using Ajax

Someone can help me? There is a working form for sending messages to email.
<form enctype="multipart/form-data" role="form" id="form" method="post" action="handler.php">
<div class="form-row">
<div class="form-group col-sm-6">
<label for="name" class="nameForInput">Name:</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Enter name" >
</div>
<div class="form-group col-sm-6">
<label for="email" class="nameForInput">Email:</label>
<input type="mail" name="email" class="form-control" id="email" placeholder="Enter email" >
</div>
</div>
<div class="form-group">
<label for="phone" class="nameForInput">Phone:</label>
<input class="form-control phone" name="phone" type="text" placeholder="+3 (000) 000-00-00" >
</div>
<div class="form-group">
<label for="message" class="nameForInput">Message:</label>
<textarea id="message" class="form-control" name="message" rows="5"placeholder="Enter your message" ></textarea>
</div>
<div class="form-group">
<label for="myfile" class="file-label left">
<img src="img/upload.svg" alt="">
<p class="amount">To attach files</p>
</label>
<input type="file" class="my" id="myfile" name="myfile[]" multiple>
</div>
<div class="form-group">
<input id="check" name="check" checked type="checkbox">
<span class="check-text">I confirm my consent to the processing of personal data</span>
</div>
<button type="submit" class="btn btn-success btn-lg">Send</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="img/loader.gif" alt=""></span>
</div>
</form>
ajax:
var form = $('#form'),
button = $('.btn'),
answer = $('#answer'),
loader = $('#loader');
$.ajax({
url: 'handler.php',
type: 'POST',
contentType: false,
processData: false,
data: new FormData(this),
beforeSend: function() {
answer.empty();
button.attr('disabled', true).css('margin-bottom', '20px');
loader.fadeIn();
},
success: function(result) {
loader.fadeOut(300, function() {
answer.text(result);
});
form[0].reset();
button.attr('disabled', false);
},
error: function() {
loader.fadeOut(300, function() {
answer.text('An error occurred! Try later.');
});
button.attr('disabled', false);
}
});
});
});
ContactMailer.php:
<?php
class ContactMailer
{
/**
* Sender's E-mail
* #var string
*/
private static $emailFrom = 'somemail#mail.com';
/**
* Recipient's E-mail
* #var string
*/
private static $emailTo = 'somemail#mail.com';
/**
* Sends an email if the email is sent,
* Returns TRUE, otherwise FALSE.
* #param string $name
* #param string $email
* #param string $phone
* #param string $message
* #return boolean
*/
public static function send($name, $email, $phone, $message)
{
// We form a letter body
$body = "Name: " . $name . "\nE-mail: " . $email . "\nPhone: " . $phone . "\n\nMessage:\n" . $message;
// Create PHPMailer object
$mailer = new PHPMailer(true);
// Connection settings
$mailer->isSMTP();
// Installs the mail server host (Mail.ru: smtp.mail.ru, Google: smtp.gmail.com)
$mailer->Host = 'smtp.mail.com';
// Includes SMTP authorization
$mailer->SMTPAuth = true;
// Entire login or E-mail
$mailer->Username = self::$emailFrom;
// Mailbox Password
$mailer->Password = '';
// Protocol of connection
$mailer->SMTPSecure = '';
// Port for outgoing mail
$mailer->Port = '';
// Establishes coding
$mailer->CharSet = 'UTF-8';
// Sets E-mail and sender name
$mailer->setFrom(self::$emailFrom, $name);
// Adds recipient 's E-mail
$mailer->addAddress(self::$emailTo);
// Control of a HTML-format
$mailer->isHTML(false);
// Letter subject
$mailer->Subject = 'Feedback form completed';
// Main body of the letter
$mailer->Body = $body;
// Send the letter
if ($mailer->send()) {
return true;
}
return false;
}
}
handler.php:
<?php
require_once __DIR__ . '/mailer/Validator.php';
require_once __DIR__ . '/mailer/ContactMailer.php';
if (!Validator::isAjax() || !Validator::isPost()) {
echo 'Access is forbidden!';
exit;
}
$name = isset($_POST['name']) ? trim(strip_tags($_POST['name'])) : null;
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : null;
$phone = isset($_POST['phone']) ? trim(strip_tags($_POST['phone'])) : null;
$message = isset($_POST['message']) ? trim(strip_tags($_POST['message'])) : null;
//protection against XSS
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//Issues an error if the download size exceeds the limit set by the server
if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0)
{ echo "CONTENT SIZE EXCEEDS THE LIMIT";
exit;}
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo 'All fields are required.';
exit;
}
if (!Validator::isValidName($name)) {
echo 'Name does not match format (name must contain only letters).';
exit;
}
if (!Validator::isValidEmail($email)) {
echo 'E-mail does not conform to the format.';
exit;
}
if (!Validator::isValidPhone($phone)) {
echo 'Phone doesn\'t match format.';
exit;
}
if (ContactMailer::send($name, $email, $phone, $message)) {
echo htmlspecialchars($name) . ', your message was sent successfully.';
} else {
echo ' An error occurred! Failed to send message.';
}
exit;
?>
css:
#answer {
color: #ff5b5b;
}
Everything works, but all messages are displayed in red because the styles for # answer are set to red. But it is necessary that in case of successful submission of forms messages are displayed in green color, and in case of errors - in red. Tried adding this:
success: function(result) {
loader.fadeOut(300, function() {
if (result === 'ok') {
answer.text(result).addClass('success');
} else {
answer.text(result).addClass('error');
}
});
form[0].reset();
button.attr('disabled', false);
},
css:
.success {
color: #218838;
}
.error {
color: #ff5b5b;
}
but only the class 'error' is always added, and if the submission is successful as well. Also tried in the file handler.php simply stick styles to the message:
if (ContactMailer::send($name, $email, $phone, $message)) {
echo htmlspecialchars($name) . '<span style="color: #218838;">, your message was sent successfully.</span>';
} else {
echo 'An error occurred! Failed to send message.';
}
exit;
but nothing applies, issues just a message along with tags:
'<span style="color: #218838;">, your message was sent successfully.</span>'
Although if you create just some other php file, there the message in echo is displayed in green, does not work in this handler.php file.
Someone can suggest how to properly make the switch in Ajax so that the message is displayed green when successfully sent and why css styles are not applied in handler.php.
It never enters the code for success because result is never set to 'ok' but to a long successful message.
success: function(result) {
loader.fadeOut(300, function() {
if (result.includes('your message was sent successfully')) {
answer.text(result).addClass('success');
} else {
answer.text(result).addClass('error');
}
});
form[0].reset();
button.attr('disabled', false);
},
One more.
ContactMailer:
// Send the letter
if ($mailer->send()) {
return true;
}
return false;
handler.php:
require_once __DIR__ . '/mailer/Validator.php';
require_once __DIR__ . '/mailer/ContactMailer.php';
if (!Validator::isAjax() || !Validator::isPost()) {
$data['error'] = 'Access is forbidden!';
echo json_encode($data);
exit;
}
$data = array();
$name = isset($_POST['name']) ? trim(strip_tags($_POST['name'])) : null;
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : null;
$phone = isset($_POST['phone']) ? trim(strip_tags($_POST['phone'])) : null;
$message = isset($_POST['message']) ? trim(strip_tags($_POST['message'])) : null;
//protection against XSS
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//Issues an error if the download size exceeds the limit set by the server
if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) {
$data['error'] = "CONTENT SIZE EXCEEDS THE LIMIT";
echo json_encode($data);
exit;
}
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
$data['error'] = 'All fields are required.';
echo json_encode($data);
exit;
}
if (!Validator::isValidName($name)) {
$data['error'] = 'Name does not match format (name must contain only letters).';
echo json_encode($data);
exit;
}
if (!Validator::isValidEmail($email)) {
$data['error'] = 'E-mail does not conform to the format.';
echo json_encode($data);
exit;
}
if (!Validator::isValidPhone($phone)) {
$data['error'] = 'Phone doesn\'t match format.';
echo json_encode($data);
exit;
}
if (ContactMailer::send($name, $email, $phone, $message)) {
$data['success'] = htmlspecialchars($name) . ', your message was sent successfully.';
echo json_encode($data);
} else {
$data['error'] = 'An error occurred! Failed to send message.';
echo json_encode($data);
}
exit;
ajax:
$(function() {
$('#form').on('submit', function(e) {
e.preventDefault();
var form = $('#form'),
button = $('.btn'),
answer = $('#answer'),
loader = $('#loader');
answer.removeClass('error success');
$.ajax({
url: 'handler.php',
type: 'POST',
contentType: false,
processData: false,
dataType: "json",
data: new FormData(this),
beforeSend: function() {
answer.empty();
button.attr('disabled', true).css('margin-bottom', '20px');
loader.fadeIn();
},
success: function(data) {
loader.fadeOut(300, function() {
if (data.error) {
answer.text(data.error).addClass('error');
} else {
answer.text(data.success).addClass('success');
}
});
form[0].reset();
button.attr('disabled', true);
},
error: function() {
loader.fadeOut(300, function() {
answer.text('An error occurred! Try later.').addClass('error');
});
button.attr('disabled', true);
}
});
});
});
In this method in ajax necessarily add dataType: "json".
One more way.
ContactMailer.php:
// Send the letter
if ($mailer->send()) {
return true;
} else {
echo 'no';
return false;
}
handler.php:
if (ContactMailer::send($name, $email, $phone, $message)) {
echo 'yes';
} else {
echo 'An error occurred! Failed to send message.';
}
exit;
ajax:
success: function(data) {
loader.fadeOut(300, function() {
if (data === "yes") {
answer.text("Your message was sent successfully.").addClass('success');
} else {
answer.text(data).addClass('error');
}
});
form[0].reset();
button.attr('disabled', true);
},
To switch correctly before calling ajax, we also delete the answer. removeClass ('error success') class as in the example above, otherwise two classes will be added to the answer at once.

Ajax form submit returns 404 error on submit

I used Mobirise to create a bootstrap based website with a contact form towards the end of it. The form originally had an action just taking it to the Mobirise website. I have previously used ajax and PHP to create mailer forms, and so modified files I had on hand to handle this form. However, whenever I click on the submit button, I get the following error in the console:
POST http://www.mywebsite.com/captcha-lib.php 404 (Not Found)
I have checked and verified that php is enabled on the server (Bluehost), and that the file in question is along the correct path, and that it is on the remote server (it is). Can anyone help me determine why I am getting this error? I have provided the HTML, Ajax, and PHP for all relevant elements below, with private keys and data removed.
Below is the html for the form itself:
<form data-form-title="Let's Work Together">
<input type="hidden" value="3S/6rrqxqgfL9WCp8yG49uE1861hrI6n4k9XNv8Q5Awspyeq+y1eU1g/jgUsPbIH+KZRWaBHkHuhzqxyJ39m7DSH7QZBYD6IZFqS6415lGnscjkO2Frp6/UUrh4xDIED" data-form-email="true">
<div class="col-xs-12 col-md-8 col-md-offset-2 form-wrap">
<div class="col-xs-12">
<div class="form-group">
<label class="form-control-label">Name*</label>
<input type="text" class="form-control" id="name" name="name" required="" data-form-field="Name" placeholder="Name*">
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label class="form-control-label">Email*</label>
<input type="email" class="form-control" id="email" name="email" required="" data-form-field="Email" placeholder="Email*">
</div>
</div>
<div class="col-xs-12">
<label class="form-control-label">Please leave a detailed message and include the type of project you have, as well as how extensive it is.</label>
<textarea class="form-control" id="message" name="message" rows="7" data-form-field="Message" placeholder="Please leave a detailed message and include the type of project you have, as well as how extensive it is."></textarea>
</div>
<div style="float: left;" class="g-recaptcha" data-sitekey="6LetWgITAAAAANNDaTINxoYz9xyOkp2rchwrQMbX"></div>
</div>
<div class="clear"></div>
<div class="form-separator"></div>
<div class="col-xs-12 col-md-8 col-md-offset-2 form-button-wrap">
<div class="text-xs-center text-md-right"><button type="submit" class="btn btn-lg btn-primary"><span class="fa fa-send mbr-iconfont mbr-iconfont-btn" style="color: rgb(255, 255, 255);"></span>Email Me</button></div>
</div>
</form>
I am handling the form using ajax, and I added captcha to decrease the chance of spam emails. The javascript/ajax, which is at the end of the html document is as follows:
<script type="text/javascript">
function validateEmail(email) {
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(email);
}
$('form').submit(function(e) {
var getErrors = [];
e.preventDefault();
$(this).find('input').each(function(){
if($(this).val() == "" && $(this).is(':visible')) {
$(this).addClass('is-required');
getErrors.push($(this).attr('id'));
} else {
$(this).removeClass('is-required');
}
if($(this).attr('id') == "email") {
var testEmail = $(this).val();
if(validateEmail(testEmail)){
$(this).removeClass('is-required');
} else {
$(this).addClass('is-required');
getErrors.push($(this).attr('id'));
}
}
})
$(this).find('textarea').each(function(){
if($(this).val() == "") {
$(this).addClass('is-required');
getErrors.push($(this).attr('id'));
if($(this).hasClass('g-recaptcha-response')) {
$('.g-recaptcha').addClass('is-required')
}
} else {
$(this).removeClass('is-required');
if($(this).hasClass('g-recaptcha-response')) {
$('.g-recaptcha').removeClass('is-required')
}
}
})
if(getErrors.length < 1) {
$('.form-container form, .form-container .title').hide();
$('.form-container .sending').show();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
var captcha = $('#g-recaptcha-response').val();
$.ajax({
type: "POST",
url: "captcha-lib.php",
data:{
"name": name,
"email": email,
"message": message,
"g-recaptcha-response": captcha
}
}).done(function(data){
$('.form-container .success').show();
$('.form-container .sending').hide();
}).fail(function(data){
$('.form-container .failed').show();
$('.form-container .sending').hide();
});
}
return false;
})
</script>
The captcha-lib.php file was originally in a folder along the path assets/php, where the assets folder was in the website root folder. I have since moved captcha-lib.php into the root folder, so that it is in the same location as the index.html file containing the ajax. Here is the code in captcha-lib.php:
<?php
header("Access-Control-Allow-Origin: https://www.google.com");
class ReCaptchaResponse
{
public $success;
public $errorCodes;
}
class ReCaptcha
{
private static $_signupUrl = "https://www.google.com/recaptcha/admin";
private static $_siteVerifyUrl =
"https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_2.0";
function ReCaptcha($secret)
{
if ($secret == null || $secret == "") {
die("To use reCAPTCHA you must get an API key from <a href='"
. self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
}
$this->_secret=$secret;
}
private function _encodeQS($data)
{
$req = "";
foreach ($data as $key => $value) {
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req=substr($req, 0, strlen($req)-1);
return $req;
}
private function _submitHTTPGet($path, $data)
{
$req = $this->_encodeQS($data);
$response = file_get_contents($path . $req);
return $response;
}
public function verifyResponse($remoteIp, $response)
{
// Discard empty solution submissions
if ($response == null || strlen($response) == 0) {
$recaptchaResponse = new ReCaptchaResponse();
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = 'missing-input';
return $recaptchaResponse;
}
$getResponse = $this->_submitHttpGet(
self::$_siteVerifyUrl,
array (
'secret' => $this->_secret,
'remoteip' => $remoteIp,
'v' => self::$_version,
'response' => $response
)
);
$answers = json_decode($getResponse, true);
$recaptchaResponse = new ReCaptchaResponse();
if (trim($answers ['success']) == true) {
$recaptchaResponse->success = true;
} else {
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = $answers [error-codes];
}
return $recaptchaResponse;
}
}
// your secret key
$secret = MY SECRET CAPTCHA KEY;
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
// TODO change to jmceuen#shawsheencc.com
$email_to = "MYEMAILADDRESS"; // TODO - update when site is live
$noreply = "Me<MYEMAILADDRESS>"; // TODO - update when site is live
$autogreet = "Thank you for contacting me regarding my services! I will respond to your email as soon as I can. Please be patient in the meantime!\n";
$email_subject = "Me, Web Designer'";
$name = $_POST['name']; // required
$email = $_POST['email']; // required
$message = $_POST['message']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "".clean_string($message)."\n";
$email_message .= "".clean_string($name)."\n";
$email = $name.'<'.$email.'>';
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
} else {
header("HTTP/1.0 404 Not Found");
// TODO find a way to email an issue #mail("MYEMAILADDRESS", "There is an issue with php emailer", "The php resolved a 404. Please contact your web developer to resolve the issue.", "donotreply#scc.com");
}
?>

Contact form don't send well

I have a problem when sending data to the contact form. Data is sent to e-mail only if you click many times, but if you tab to move to the button and press enter data is sent immediately. But still fall into the spam.
HTML
<div id="f1" class="contact_wrapper">
<form>
<div id="r2"></div>
<input type="text" name='rname' id="names" class="name" placeholder="Ваше имя">
<input type="email" name='email' id="eml" class="email" placeholder="Ваше Email">
<input type="text" name='subject' id="phon" class="contact_number" placeholder="Контактный телефон">
<textarea name="message" id="masage" cols="30" rows="10"></textarea>
<input name="" id="button" type="button" value="Отправить" class="submit" onclick="mail2('Радиус-01 Оформить заявку - последняя форма','names','eml','phon','masage','f1','r2')">
</form>
</div>
AJAX
<script>
function mail2(subject,names,eml,phon,masage,f,rr){
var names = document.getElementById(names).value;
var eml = document.getElementById(eml).value;
var phon = document.getElementById(phon).value;
var masage = document.getElementById(masage).value;
var frt = document.getElementById('generator_konr').value;
var params = {subject:subject,names:names,eml:eml, phon:phon,masage:masage,kon:frt};
$.ajax({
type: "POST",
url: "mail2.php",
data: params,
success: function(data){
$('#ertretgfdg').html(data).fadeIn("slow");
}
});
}
</script>
mail2.php
<?
### Referals script start
$debug=0;
function writelog($s) {
global $lf,$debug;
if ($debug)
fputs($lf,"$s\n");
}
if ($debug)
$lf=#fopen(dirname(__FILE__).'/'.'debug.log','a');
$t=date('Y-m-d H:i:s');
$utm='нет';
$term='нет';
$ip=$_SERVER['REMOTE_ADDR'];
$utmdata='';
writelog("Session started (zakaz.php) at '$t', IP='$ip'");
writelog("REQUEST: ".print_r($_REQUEST,true));
if (isset($_COOKIE['utmdata'])) {
writelog("Found saved cookie UTMdata");
$utmdataexp=explode('&',$_COOKIE['utmdata']);
if (count($utmdataexp)>=2 && !empty($utmdataexp[0]) && !empty($utmdataexp[1])) {
$t=$utmdataexp[0];
$utm=$utmdataexp[1];
$term=isset($utmdataexp[2]) ? $utmdataexp[2] : 'нет';
$utmdata=$t.'&'.$utm.'&'.$term;
}
}
writelog("UTMdata is '$utmdata'");
### Referals script end
$phon = $_POST['phon'];
$names = $_POST['names'];
$subject = $_POST['subject'];
$kon = $_POST['kon'];
$eml = $_POST['eml'];
$masage = $_POST['masage'];
if ($names=='' or $names=='Введите ваше имя') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите свое имя");</script>';
exit;
}
if ($phon=='' or $phon=='Ваш телефон' or $phon=='Введите номер телефона') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите номер телефона");</script>';
exit;
}
if ($eml=='' or $eml=='Ваш email' or $eml=='Введите ваш email') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваш email");</script>';
exit;
}
if ($masage=='' or $masage=='Ваше сообщение' or $masage=='Введите ваше сообщение') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваше сообщение");</script>';
exit;
}
$er=null;
if ($subject=='Выбран конкретный генератор') {
$ert='Генератор: '.$kon.'<br/>';
}
$body ='
По вопросу: '.$subject.'<br/>
'.$ert.'
Имя: '.$names.'<br/>
Телефон: '.$phon.'<br/>
Мыло: '.$eml.'<br/>
Сообщение: '.$masage.'<br/>
Рекламная площадка:</b> '.$utm.'<br />
Ключевое слово: '.$term.'<br />
';
$email='myemail#gmail.com';
$headers = "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: <".$em.">\r\n";
if (mail($email, $subject_t, $body, $headers)) {
echo '<script>$().toastmessage(\'showSuccessToast\', "Сообщение успешно отправлено");</script>
<script>$(".header .sform").delay( 2000 ).slideToggle();</script>';
exit;
} else {
echo '<script>$().toastmessage(\'showErrorToast\', "Ошибка, повторите попытку");</script>';
exit;
}
?>
<!--

How to eliminate a Uncaught TypeError?

email.comusing this html code:
<form id="emailform" name="emailform" method="post" action="" >
<label>Name</label>
<input type="text" name="name" />
<label >Email</label>
<input type="text" name="email" />
<label >Message</label>
<textarea name="message"></textarea>
<div id="errormessage"></div>
<input type="submit" value="send" class="button" />
<input id="hiddenID" type="reset" name="hidden" />
</form>
with this script:
$("#emailform").submit(function(){
$.ajax({
type: "POST",
url: "email.ajax.php",
data: $("#emailform").serialize(),
dataType: "json",
success: function(msg){
$("#errormessage").removeClass('error');
$("#errormessage").addClass(msg.status);
$("#errormessage").html(msg.message);
$("#hiddenID").click();
},
error: function(){
$("#errormessage").removeClass('success');
$("#errormessage").addClass('error');
$("#errormessage").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
and this php:
<?php
function checkEmail($email){
if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = split("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
$response_array = array();
if(empty($_POST['name'])){
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
} elseif(!checkEmail($_POST['email'])) {
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
} elseif(empty($_POST['message'])) {
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
} else {
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail("email#email.com", "Portfolio", $body);
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
I'm getting a "Uncaught TypeError: Cannot read property 'status' of null" error at success msg and cant seem to figure why. It catches the name error but then doesnt like the email validation. Any help?
Here is the line creating the error: $("#errormessage").addClass(msg.status);
You are trying to access the status property of the msg object and the error is telling you that msg is either not an object or it has no property named status.
Do a console.log(msg); on the first line of your callback function to see what is actually being returned to the JavaScript.
Try adding this before your echo:
header('Content-type: application/json');
echo json_encode($response_array);

Categories