PHPmailer and vanilla JavaScript AJAX form prompt - javascript

So, I needed a contact form that can send emails with a "success" prompt that appears in my form, WITHOUT reloading. I have found PHPmailer that helps with sending mail to the inbox and not spam (this alone works fine, email sent straight to inbox). I then add the JS validation then AJAX, then the PHP that deals with the JSON response.
The "success" prompt appears when I click "send" (good!) but the problem is that no email has been sent/received. The code without the AJAX works fine on both my local and web hosts perfectly. How do I optimize this so the success prompt appears and the email is sent (inbox, ideally)?
No jQuery or any extra plugins please.
Thanks in advance.
HTML:
<div class="contact-form">
<form action="mail.php" method="POST" onsubmit="return doRegister()">
<input id="mail-name" type="text" name="name" placeholder="Your Name">
<span id="name-alert"></span>
<input id="mail-email" type="text" name="email" placeholder="Your Email">
<span id="email-alert"></span>
<input id="mail-subject" type="text" name="subject" placeholder="Your Subject">
<span id="subject-alert"></span>
<textarea id="mail-message" name="message" placeholder="Your Message"></textarea>
<span id="message-alert"></span>
<input type="submit" value="Send">
<input type="reset" value="Clear">
<span class="contact__form--alert-success" id="success-alert"></span>
</form>
</div>
JS:
function doRegister() {
let checks = {
name : document.getElementById("mail-name"),
email : document.getElementById("mail-email"),
subject : document.getElementById("mail-subject"),
message : document.getElementById("mail-message")
},
error = "";
if (checks.name.value=="") {
error += document.getElementById("name-alert").innerHTML+='<p>A name is required!</p>';
}
if (checks.subject.value=="") {
error += document.getElementById("subject-alert").innerHTML+='<p>A subject is required!</p>';
}
if (checks.message.value=="") {
error += document.getElementById("message-alert").innerHTML+='<p>A message is required!</p>';
}
let pattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(checks.email.value.toLowerCase())) {
error += document.getElementById("email-alert").innerHTML+='<p>A valid email is required!</p>';
}
// Ajax
if (error!="") {
error="";
} else {
let data = new FormData();
for (let k in checks) {
data.append(k, checks[k].value);
}
let xhr = new XMLHttpRequest();
xhr.open('POST', "mail.php", true);
xhr.onload = function(){
let res = JSON.parse(this.response);
// SUCCESS!
if (res.status) {
document.getElementById("success-alert").innerHTML+='<p>Success!</p>';
} else {
// ERROR!
error = "";
for (let e of res['error']) {
error += e + "\n";
}
alert(error);
}
};
// SEND
xhr.send(data);
}
return false;
}
PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$error = [];
$msg = '';
if ( array_key_exists( 'email', $_POST ) ) {
date_default_timezone_set( 'Etc/UTC' );
require 'mail/vendor/autoload.php';
// Call super globals from the contact form names
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'mail.host.com';
$mail->SMTPAuth = true;
$mail->Username = 'name#host.com';
$mail->Password = 'password1';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom( 'name#host.com', 'New Message' );
$mail->addAddress( 'somemail#mail.com' );
if ($mail->addReplyTo($email, $name)) {
$mail->Subject = $subject;
$mail->isHTML(false);
$mail->Body = <<<EOT
Email: {$email}
Name: {$name}
Message: {$message}
EOT;
}
// Check inputs
if ($name=="") {
$error[] = "A name is required.";
}
if ($subject=="") {
$error[] = "A subject is required.";
}
if ($message=="") {
$error[] = "A message is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "A valid email is required.";
}
// JSON encode with a response
echo json_encode([
"status" => count($error)==0 ? 1 : 0,
"error" => $error
]);
}
Solution:
the "send()" function was missing
if(empty($error)){
if(!$mail->send()){
$error[] = 'There was an error sending the mail. Please try again!';
}
}

Your PHP script doesn't send the mail because the send() function is not called, so after the validation, you should add something like:
if(empty($error)){
if(!$mail->send()){
$error[] = 'There was an error sending the mail. Please try again!';
}
}
echo json_encode([
"status" => count($error)==0 ? 1 : 0,
"error" => $error
]);
This way you're sending the mail and, if there was a problem(send() returns false), an error is being added to your error array.

Related

Contact form with PHP Mailer, which refreshes whole page when clicking Send

I did contact form with PHP Mailer, JavaScript and Ajax call
Everything works fine, expect javascript after clicking on button. (I even recieve an email sucessfully)
My html code:
<form id="contact-form" class="contact">
<div class="col-md-6">
<input type="text" name="name" id="fullname" placeholder="Fullname">
</div>
<div class="col-md-6">
<input type="email" name="email" id="email" placeholder="Email adress">
</div>
<div class="col-md-12">
<textarea id="message" name="message" placeholder="Message"></textarea>
</div>
<div class="col-md-12">
<button id="gumb" type="button" class="btnc" onclick="validateContact();">Send</button>
</div>
</form>
</div>
<div class="col-md-12">
<div id="response_brought"></div><!-- This will display the response from the server -->
<p> </p>
</div>
JavaSript code (This works fine, but after i press button, I RECIEVE EMAIL but my last response stays the same.. it doesn't change. It display response from fullname=="" ('Please enter your fullname in the required field to proceed. Thanks.').. So I guess there is an error inside Ajax call
function validateContact() {
"use strict";
var valid = true;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var formData = {
fullname: $("#fullname").val(),
email: $("#email").val(),
message: $("#message").val(),
};
var fullname = $("#fullname").val();
var emailreg = $("#email").val();
var message = $("#message").val();
//dataString = {'fullname': fullname, 'email': email, 'message': message, 'submitted': '1'};
if (fullname === "") { //Validation against empty field for fullname
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Please enter your fullname in the required field to proceed. Thanks.</div>');
$("#fullname").focus();
valid = false;
} else if (emailreg === "") { //Validation against empty field for email address
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Please enter your email address in the required email field to proceed. Thanks.</div>');
$("#email").focus();
valid = false;
} else if (reg.test(emailreg) === false) { //Validation for working email address
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Sorry, your email address is invalid. Please enter a valid email address to proceed. Thanks.</div>');
$("#email").focus();
valid = false;
} else if (message === "") { //Validation against empty field for email message
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Please enter your message in the required message field to proceed. Thanks.</div>');
$("#message").focus();
valid = false;
}
valid = true;
$.ajax({
type: "POST",
url: "sendemail.php",
data: formData,
success:function(data){
var response_brought = response.indexOf('Congrats');
$(".contact-form").slideUp(500);
$("#response_brought").html(response);
setTimeout(function () {
$("#response_brought").html('');
}, 10000);
},
error:function (){}
});
}
Error in my console: ERROR
And my php code:
use PHPMailer\PHPMailer\PHPMailer;
require_once 'phpmailer/src/Exception.php';
require_once 'phpmailer/src/PHPMailer.php';
require_once 'phpmailer/src/SMTP.php';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Mailer = "smtp";
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = True;
$mail->Host = "smtp host";
$mail->Username = "myemail";
$mail->Password = "****";
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = '587';
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = $error = '';
if (!empty($fullname) && !empty($email) && !empty($message)) {
try {
$mail->setFrom('myemail');
$mail->addAddress('myemail');
$mail->isHTML(true);
$mail->Subject = 'Mail poslan iz spletnega obrazca';
$mail->Body = "Ime: " . $_POST["fullname"] . "<br> Email: " . $_POST["email"] . "<br>";
$mail->Body .= $message;
$mail->send();
$success = "Message sent successfully";
} catch (Exception $e) {
$error = "Sorry message could not send, try again";
}
}
Thank you for your help

PHP/Javascript validation works partially

I have Javascript/Ajax and PHP validation for my form. It's displays the errors if the form filled incorrectly, but it won't work and let me submit the form even if there is no errors. Basically ,when I click the submit button it stays at the same page and won't do anything.
In console I got the next error on submit: Failed to load file:///C:/Users/ilona/Desktop/BootstrapLandinPage/send.php: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. jquery-2.2.4.min.js:4. I run my project on XAMPP.
My HTML:
<section class="inspiration" id="three">
<div class="overlay">
<div class="container">
<div class="row">
<article class="col-md-12 text-center">
<div class="intermediate-container">
<div class="heading">
<h2>יש לכם שאלה? צרו איתי קשר</h2>
</div>
<div class="row">
<div class="col-md-3 col-sm-3"></div>
<div class="col-md-6 center-block col-sm-6 ">
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
<span class='error-message' id='subject-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
<span class='error-message' id='message-error'></span>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<span class="success">Thank's for submitting the form</span>
</form>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
</section>
<!-- [/CONTACT] -->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validateform.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
My validateform.js:
$(document).ready(function(){
function jsShow(id) {
$('#'+id).show();
}
function jsHide(id) {
$('#'+id).hide();
}
function producePrompt(message, promptLocation, color) {
$('#'+promptLocation).text(message).css('color', color).show();
}
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i.test(value);
}, "Letters only please");
jQuery.validator.addMethod("digitsonly", function(value, element) {
return this.optional(element) || /([0-9\s\-]{7,})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/.test(value);
}, "Include only digits| min :8 ");
$('.success').hide();
$("#mc-form").validate({
error: function(label) {
$(this).addClass( "error" );
},
rules: {
name: {
required: true,
lettersonly: true
},
phone: {
required: true,
digitsonly: true
},
email: {
required: true,
email: true
},
subject: {
required: true,
minlength: 2
},
message: {
required: true,
minlength: 2
}
},
messages: {
name: {
required: "Please specify your name",
lettersonly: "Letters only please"
},
phone: {
required: "Phone number is required",
digitsonly: "Include only digits| min :8 "
},
email: {
required: "Email is required",
email: "Email Invalid"
},
subject: {
required: "Subject is required"
},
message: {
required: "Message is required"
}
},
submitHandler: function(form) {
sendForm();
}
});
function sendForm() {
$('[id*="-error"]').text(''); // default hide all error messages
event.preventDefault(); // prevent form submission and therefore page reload
$.ajax({
type: 'POST',
url: './send.php',
data: $("#mc-form").serialize(),
success: function(data) {
if(data.hasOwnProperty('error')) {
Object.keys(data['error']).forEach(function(key) {
producePrompt(data['error'][key], key+'-error', 'red');
});
}
if(data.hasOwnProperty('mail_error')) {
alert('Could not send mail');
}
if(data.hasOwnProperty('success')) {
$('.success').show();
}
}
});
}
});
My send.php:
$error_msg = array();
$success_msg = array();
$data = '';
// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error_msg['name'] = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$error_msg['name'] = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$error_msg['email'] = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg['email'] = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$error_msg['phone'] = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$error_msg['phone'] = "Invalid phone number";
}
}
if (empty($_POST["subject"])) {
$error_msg['subject'] = "Subject is required";
}
if (empty($_POST["message"])) {
$error_msg['message'] = "Message is required";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if (empty($error_msg)){ // note that $lastname_error does not exists
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'xxxxxxxxx#gmail.com';
$subjectm = 'Contact Form Submit';
if (mail($to, $subjectm, $message)){
$success_msg = "Message sent, thank you for contacting us!";
$name = $email = $phone = $message = $subject = '';
} else {
$mail_error_msg = 'Could not send email';
}
}
// set output data accordingly
if(!empty($success_msg)) {
$data = array('success'=>$error_msg);
} else if(!empty($error_msg)) {
$data = array('error'=>$error_msg);
} else if(!empty($mail_error_msg)) {
$data = array('mail_error'=>$mail_error_msg);
}
// output json that you can parse with jquery
header('Content-Type: application/json');
echo json_encode($data);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
You are opening the file directly unless you configured it in Apache. The file seems to not have connection to your web server XAMPP.
You need to do following:
Copy BootstrapLandinPage directory to c:/xampp/htdocs
Add virtual host to XAMPP
Open the file C:\xampp\apache\conf\extra\httpd-vhosts.conf and add this snippet, adapted to your environment.
<VirtualHost 127.0.0.2:80>
ServerName playground.localhost
ServerAlias playground.localhost
DocumentRoot c:/xampp/htdocs/your_website
<Directory "c:/xampp/htdocs/your_website/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Restart Apache in control panel of XAMPP (click XAMPP icon in bottem right in Windows)
Open browser and enter IP address 127.0.0.2 (the one you assign in virtual host)
Now you site should appear with PHP capabilities.
UPDATE
After the latest comment i add here a way to send emails via localhost.
Use a PHP library to send mails from email address of your domain provider:
Download PHPMailer
Copy the ZIP contents into a separate directory in BootstrapLandinPage. For example: lib/PHPMailer
Add these lines to the top of you process.php
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
Add the example snippet on the documentation page where you downloaded the package and ajust to your needs.
Alternatively for local mailing:
Download hmailserver
Install it following their tutorial
Navigate to C:\Windows\System32\drivers\etc\hosts file and open it as administrator
Add following line:
127.0.0.1 localhost localhost.com
Add user example#localhost.com to your hmailserver
Configure mail account in your mailing app using:
Username: example#localhost.com
Password: your_password
IMAP/SMTP Server: localhost
UPDATE 2
This would be your PHP code using PHPMailer:
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
$error_msg = array();
$success_msg = array();
$data = '';
// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error_msg['name'] = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$error_msg['name'] = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$error_msg['email'] = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg['email'] = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$error_msg['phone'] = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$error_msg['phone'] = "Invalid phone number";
}
}
if (empty($_POST["subject"])) {
$error_msg['subject'] = "Subject is required";
}
if (empty($_POST["message"])) {
$error_msg['message'] = "Message is required";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if(!empty($error_msg)) {
$data = array('error'=>$error_msg);
outputJson($data);
} else { // note that $lastname_error does not exists
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'xxxxxxxxx#gmail.com';
$subjectm = 'Contact Form Submit';
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'some_user#gmail.com';
$mail->Password = 'some_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//Recipients
$mail->setFrom('some_user#gmail.com', 'Your name');
$mail->addAddress($email, $name);
//Content
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submit';
$mail->Body = $message;
$mail->AltBody = preg_replace( "/\n\s+/", "\n", rtrim(html_entity_decode(strip_tags($message))) ); // For clients that do not support html / "spam control"
$mail->send();
$data = array('success'=>'Message sent, thank you for contacting us!');
outputJson($data);
} catch (Exception $e) {
$data = array('mail_error'=>'Could not send email');
outputJson($data);
//echo 'Mailer Error: ' . $mail->ErrorInfo; // Debug message that you can see in network tab in web developer browser extension
}
$name = $email = $phone = $message = $subject = '';
}
}
// return data in json format
function outputJson($data) {
// output json that you can parse with jquery
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

Detect PHP Mailer error and print the message in the website using jquery

I am using PhpMailer to send emails. Inside my own script I want to parse some javascript inside the below if statement. Note that I have html enabled.
When the email is not sent I want to parse some javascript inside the .done function that the email is not sent. eg complete.html("Message Not Sent!"); When the email is sent, I want to show that the email is sent. How can I do that and where is better to do that, inside php file or inside the javascript?
var form = $('#contact');
form.submit(function(event) {
event.preventDefault();
var complete = $('#formAppend');
var $form = $(this);
var name = $("#fname").val();
var email = $("#email").val();
var Message = $("#msg").val();
var countryoption = $("#country").val();
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country: countryoption
},
beforeSend: function() {
complete.html('Message is Sending...').fadeIn();
}
})
.done(function(data) {
//This should change depending on the php if statement at the bottom.
complete.html("Message Sent");
});
}); //end contact form
<form id="contact" method="post" action="#ss">
<div id="formAppend"></div>
<input type="text" id="fname" name="firstname" placeholder="Το όνομα σας.." required>
<input type="email" id="email" name="email" placeholder="Το email σας.." required>
<select id="country" required>
<option class="w3-center" value="" disabled selected value>-- Χώρα --</option>
<option value="Κυπρος">Κύπρος</option>
<option value="Ελλάδα">Ελλάδα</option>
<option value="Άλλο">Άλλη</option>
</select>
<textarea id="msg" name="message" placeholder="Γράψε το μήνυμα.." style="height:200px;max-height:400px;min-height:100px;" required></textarea>
<div id="op">
<button type="submit" style="" class="btn btn-primary img-responsive"> Αποστολή</button> </div>
</form>
PHP:
<?php
require 'PHPMailer-master/PHPMailerAutoload.php';
if(empty($_POST['Email'])){
$_POST['Email']= "";
}
if(empty($_POST['Name'])){
$_POST['Name']= "";
}
if(empty($_POST['message'])){
$_POST['message']= "";
}
if (isset($_POST["message"]) && !empty($_POST["message"])) {
$mymail=smtpmailer("webdominar1#gmail.com",$_POST['Email'], $_POST['Name'], $_POST['message']);
}else{
header('Location: http://webdominar.xyz'); exit();
}
function smtpmailer($to, $from, $from_name, $body) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SetFrom($from, $from_name);
$mail->Subject = "Εμβολιασμός Δέντρων ~ Φόρμα Επικοινωνίας ~ $body ";
$mail->CharSet = 'UTF-8';
$mail->isHTML(true); // Set email format to HTML
$Country = $_POST["Country"];
$mail->Body = "BLABLA ";//end email body
$mail->AddAddress($to);
//send the message, check for errors
if (!$mail->send()) { //Message not sent
echo "Mailer Error: " . $mail->ErrorInfo;
} else {//Message sent!
echo "Well done $from_name, your message has been sent!\nWe will reply to the following email: $from"
. "<br>Your Message: $body";
}
} //end function smtpmailer
?>
Change you PHP and JS code like this........
require 'PHPMailer-master/PHPMailerAutoload.php';
if (empty($_POST['Email'])) {
$_POST['Email'] = "";
}
if (empty($_POST['Name'])) {
$_POST['Name'] = "";
}
if (empty($_POST['message'])) {
$_POST['message'] = "";
}
if (isset($_POST["message"]) && !empty($_POST["message"])) {
$mymail = smtpmailer("webdominar1#gmail.com", $_POST['Email'], $_POST['Name'], $_POST['message']);
} else {
header('Location: http://webdominar.xyz');
exit();
}
function smtpmailer($to, $from, $from_name, $body) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SetFrom($from, $from_name);
$mail->Subject = "Εμβολιασμός Δέντρων ~ Φόρμα Επικοινωνίας ~ $body ";
$mail->CharSet = 'UTF-8';
$mail->isHTML(true); // Set email format to HTML
$Country = $_POST["Country"];
$mail->Body = "BLABLA "; //end email body
$mail->AddAddress($to);
//send the message, check for errors
if (!$mail->send()) { //Message not sent
//echo "Mailer Error: " . $mail->ErrorInfo;
$responce = array(
'message' => $mail->ErrorInfo,
'success' => FALSE,
);
echo json_encode($responce);
} else {//Message sent!
$msg = "Well done $from_name, your message has been sent!\nWe will reply to the following email: $from"
. "<br>Your Message: $body";
$responce = array(
'message' => $msg,
'success' => TRUE,
);
echo json_encode($responce);
}
}
Change your JS code like this
var form = $('#contact');
form.submit(function(event) {
event.preventDefault();
var complete = $('#formAppend');
var $form = $(this);
var name = $("#fname").val();
var email = $("#email").val();
var Message = $("#msg").val();
var countryoption = $("#country").val();
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country: countryoption
},
beforeSend: function() {
complete.html('Message is Sending...').fadeIn();
}
})
.done(function(data) {
var response=JSON.parse(data);
if(response.success == true) {
//return true
complete.html("Message Sent");
// if you want show Response message which get form sendemail.php
complete.html(data.message);
} else {
//return false
complete.html("Message Not Sent!");
// if you want show Response message which get form sendemail.php
complete.html(data.message)
}
//This should change depending on the php if statement at the bottom.
});
}); //end contact form
Change the end of your PHP to:
header("Content-type:application/json");
$message = "Well done ".$from_name.", your message has been sent!<br/>We will reply to the following email:".$from."<br>Your Message: ".$body;
if (!$mail->send()) {
echo '{"error":"'.$mail->ErrorInfo.'"}';
} else {
echo '{"success":"'.json_encode($message).'"}';
}
Then you can do this in the .done:
.done(function(data) {
if (data.error) {
complete.html(data.error).addClass("error");
}
else
complete.html(JSON.parse(data.success));
}
});

Uncaught ReferenceError: ajaxObj is not defined

Uncaught ReferenceError: ajaxObj is not definednewsletter #
main.js:22onclick # index.php:541
I am trying to develop a newsletter which will be on the footer part of the every page and it will use NAME and EMAIL to suscribe. It will grab the data entered by user from HTML form and pass it to ajax for validation after usere click submit which will pass information to newsletter.php and give back message to user if they already exist or signup sucessfull message but what happened is as User click submit button it just says "Please wait.." and keeps on loading forever giving above message on chrome cousole.
I want user to be able to sign up from any page they are on without reloading page.
The problem here is
Above Error given in Chrome cousole while I try to submit the form.
Thank you for looking at my problem. Any help will be appriciated..
HTML
<?php include_once('newsletter.php'); ?>
<form name="signupform" id="signupform" method="POST" onsubmit="return false;">
<p align="center"><strong>NEWSLETTER SIGNUP :</strong>
<input id="sus_name" name="sus_name" type="text" placeholder="Enter your Name" size="15">
<input id="sus_email" name="sus_email" type="text" placeholder="Enter your Email" size="26">
<input id="optin" name="optin" type="submit" value="SUBSCRIBE" onclick="newsletter()"><br>
<span id="status"></span>
</p>
</form>
AJAX
//News Letter Validation
function newsletter(){
var u = document.getElementById("sus_name").value;
var e = document.getElementById("sus_email").value;
var m =(document.URL);
var status = document.getElementById("status");
if(u == "" || e == ""){
status.innerHTML = "Fill out all of the form data";
} else {
document.getElementById("optin").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST","(document.URL)");//Problem with this line as i want it to post to same page where url will be dynamic
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
document.getElementById("optin").style.display = "block";
} else {
window.scrollTo(0,0);
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> ";
}
}
}
ajax.send("u="+u+"&e="+e);
}
}
newsletter.php
<?php
$msg_to_user = "";
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once "includes/mysqli_connect.php";
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = ereg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysql_real_escape_string($_POST['e']);
// GET USER IP ADDRESS
$ip = ereg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if (($u != "") && ($e != "") ){
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = $u;
$email = $e;
$sql = mysql_query("SELECT * FROM news_letter WHERE susc_email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Please type an email address ' . $name . '.</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">' . $email . ' is already in the system.</font></h4>';
} else {
$i= substr($name,0,3);
$j=rand(1000,9999);
$l= substr($email,0,3);
$k= $i.$j.$l;
$o=rand(0,9);
$m=str_replace("#","$o","$k");
$n=mysql_real_escape_string($m);
$sql_insert = mysql_query("INSERT INTO news_letter (susc_name, susc_email, susc_date, susc_code)
VALUES('$name','$email',now(),'$n')") or die (mysql_error());
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
echo "signup_success";
exit();
}
}
}
?>

Check the security of form.

My account was suspended because of SPAM several times and my host provider told me to check my website security. May be my forms are not secured enough. Do you think that this form can be used to send spam?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
html:
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
php:
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
Many thanks!
Your form would actually be not safe against bots, because you dont got any captcha or something.
2 Options for you:
Captcha
Captcha -> you got something to fill in -> you probably know this!:)
https://www.google.com/recaptcha
Honeypot
Honeypot means, you are adding hidden fields in your form. And if those hidden fields have changed - you know that a BOT has entered content in your form. Aswell, this is better than Captchas, because your User doesnt has to fill in a Captcha
I would prefer Honeypot, because I don't like forms, where i have to fill in a Captcha once or even twice, when I failed or the captcha wasnt readable.
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx/
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
another option is what I did is to use a hide field and put the time stamp on it and then compare to the time stamp on the PHP side, if it was faster than 15 seconds (depends on how big or small is your forms) that was a bot...
Taking clue from the suggestions above, I am just putting a ready code for you to use.
HTML
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="checkbot" type="hidden" name="timestamp" value="" />
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
Javascript
<script type="text/javascript">
$(document).ready(function () {
/*Set current time on the hidden field.*/
$('#checkbot').val($.now());
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
PHP
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
$checkbot = $_POST['timestamp'];
$time_diff = time() - $checkbot;
//If Time difference is less than 15 sec it's a bot
if($time_diff < 15){
exit;
}
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
In theory it can be used to send spam, because there are only checks if fields have values and as long the fields have a value, it does not care whether the input was human or a bot. You could improve the security by adding captcha codes (http://www.captcha.net/), to validate if an individual filling in your form is a human.
Try using this Spam Checker.
Useful program written in Java which looks up for spam IP Addresses using DNS lookups. Hope so it helps.

Categories

Resources