PHPMailer() ajax request - php

In my quest to validate a form with PHP and $.ajax() and send a mail to my own mail adress having as sender my own gmail adress, as subject the user name and email from the form. Bassically I want the site to notify me that an user left me a message along with his name and adress si I can answer to him. When I try to send I receive an error.
I took the script from PHPMailer example but I cannot figure out where the mail body should be. I have the php file:
<?php
error_reporting(E_ALL);
ini_set('display_errors',true);
// require_once 'class.phpmailer.php';
require 'PHPMailerAutoload.php';
sleep(1);
$mail_reg = '/^(?i)(([^<>()[\]\\.,;:\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,}))$/';
$return = array();
$mesaj = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {
$mesaj = "Please enter your name!";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {
$mesaj = "Please enter your e-mail!";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputMess'])) {
$mesaj = "Please tell us something";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "tavitudor124#gmail.com";
$mail->Password = "**********";
$mail->SetFrom('tavitudor124#gmail.com' , 'First Last');
$mail->Subject = $_POST['inputName'].'/'.$_POST['inputEmail'].'wrote';
//$mail->MsgHTML($body);
$address = 'tavi_tudor#yahoo.com';
$mail->AddAddress($address, "John Doe");
$mail->Body = $_POST['inputMess'];
if (!$mail->Send()) {
$mesaj = 'The message cannot be delivered, please try again later!';
$return['msg'] = 'The message cannot be delivered, please try again later!';
echo json_encode($return);
exit();
} else {
$mesaj = 'Thank you for getting in touch. We will contact you!';
// $return["error"] = false;
$return["msg"] = 'Thank you for getting in touch. We will contact you! '.$mail- >ErrorInfo;
echo json_encode($return);
exit();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NRDC Environmental N.G.O.</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/marin.js"></script>
</head>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<h3 class="masthead-brand">NRDC<br />Save our Planet O.N.G.</h3>
<ul class="nav masthead-nav">
<li>Home</li>
<li>Gallery</li>
<li class="active">Contact</li>
<li>Join Us</li>
</ul>
</div>
</div>
<div class="inner cover">
<div class="row">
<div class="col-xs-12" style="text-align:center;font-size:22px;">
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="inputName">Your name</label>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</div>
<div class="form-group">
<label for="inputEmail">Your e-mail</label>
<input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail">
</div>
<div class="form-group">
<label for="inputMess">Your message for us</label>
<textarea name="inputMess" class="form-control" id="inputMess"> </textarea>
</div>
<button type="submit" name="send" class="btn btn-default">Send</button>
</form>
<div id='mess'> </div>
</div>
</div>
</div>
<div class="mastfoot">
<div class="inner">
<p id="footer">©All rights reserved to NRDC, by TaoAppz</p>
</div>
</div>
</div>
</div>
</div>
JS
$(document).ready(function() {
var email_reg = /^(([^<>()[\]\\.,;:\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,}))$/i;
$('form').submit(function(event) {
event.preventDefault();
if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {
alert('Please enter your name');
} else if (!email_reg.test($('#inputEmail').val())) {
alert('Please enter a valid e-mail adress');
} else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {
alert('Please tell us something');
} else {
var formData = $('form').serialize();
submitForm(formData);
}
})
function submitForm(formData) {
$.ajax({
type: 'POST',
url: $('form').action,
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
beforeSend: function() {
$('#mess').text('Processing...');
},
success: function(data) {
$('#mess').text(data.msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#mess').text('Error! ' + textStatus + ' ' + errorThrown + ' ' + 'Please try again later!');
},
complete: function(XMLHttpRequest, status) {
//$('form')[0].reset();
}
})
}
})

It was a mistake on my include in php and the '$mail->Debugoutput = 'html' created html output that was pasrsed as JSON.
So I took out the debugg mode from PHPMailer and now I have a nice working contact form using ajax and PHPMailer. Thanks for your help

Related

jQuery Code Inside PHP File Being Displayed While Using AJAX

Whilst trying to use AJAX for validation on my website, it is completely displaying to the user with exception of the PHP variables, the jquery code I am using for styling my inputs. I am trying to change the styles of my inputs accordingly and provide and error message, which is successful, however, the javascript code is also being displayed
index.php
<html>
<head>
<link rel="stylesheet" href="css/template.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery/template.js"></script>
<script type="text/javascript" src="jquery/index.js"></script>
</head>
<body onload="startUp();">
<!-- Banner Image -->
<div id="banner"><img id="bannerImage" src="abcdefd.com.jpg" alt=""></div>
<!-- Body Wrapper -->
<div id="wrapper">
<!-- Content -->
<div id="content">
<!-- <h2 id="title">Log In</h2> -->
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<input class="click" type="submit" name="submit" id="submit" value="Log in">
</form>
<p id="err"></p>
</div>
</div>
</body>
</html>
index.js
$(document).ready(function(){
$("#loginForm").submit(function(event){
event.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
var submit = $("#submit").val();
$("#err").load("config/config.index.php",{
email: email,
password: password,
submit:submit
});
});
});
config.index.php
<?php
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = $_POST['password'];
$errEmptyAll = false;
$errEmptyEmail = false;
$errEmptyPassword = false;
$errEmail = false;
if(empty($email) && empty($password)){
echo 'Please enter an email and password.';
$errEmptyAll = true;
} else if(empty($email)){
echo 'Please enter an email.';
$errEmptyEmail = true;
} else if(empty($password)){
echo 'Please enter a password.';
$errEmptyPassword = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo 'Please enter a valid email.';
$errEmail = true;
}
}
?>
<script>
var errEmptyAll = "<?php echo $errEmptyAll; ?>";
var errEmptyEmail = "<?php echo $errEmptyEmail; ?>";
var errEmptyPassword = "<?php echo $errEmptyPassword; ?>";
var errEmail = "<?php echo $errEmail; ?>";
if(errEmptyAll == true){
$("#email, #password").addClass("inputErr");
}
if(errEmptyEmail == true){
$("#email").addClass("inputErr");
}
if(errEmptyPassword == true){
$("#password").addClass("inputErr");
}
if(errEmail == true){
$("#email").addClass("inputErr");
}
</script>
The config PHP file should not have any JS at all.
Don't use .load(). Use $.ajax to send POST data and listen for server responses.
Build a json_encode response on PHP which will be returned to the browser via AJAX. Read the response data (from PHP) in JavaScript jQuery via the :success property or in the .done() method of $.ajax
index.html
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" name="submit">Log in</button>
</form>
<p id="err"></p>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script srrc="index.js"></script>
index.js
jQuery(($) => { // DOM ready and $ alias in scope
const $err = $("#err");
$("#loginForm").on("submit", function (ev) {
ev.preventDefault(); // prevent browser submit
$(this).find(`[name]`).removeClass("inputErr");
$.ajax({
type: "POST",
dataType: "JSON",
url: this.action, // from form action value
data: $(this).serialize(),
}).done((res) => {
// res is the JSON Response from PHP
console.log(res); // Do with this whatever you want. i.e:
if (res.errors.length) {
$err.text(res.errors.join(", "));
res.fields.forEach(field => {
$(`[name="${field}"]`).addClass("inputErr");
});
} else {
// SUCCESS!!!
}
});
});
});
config/config.index.php
<?php
$response = (object)[
"status" => "error",
"errors" => [],
"fields" => [], // IDs of fields with error
];
if (
$_SERVER["REQUEST_METHOD"] === "POST" &&
isset($_POST["email"]) &&
isset($_POST["password"])
) {
$email = $_POST["email"];
$password = $_POST["password"];
$passwordEmpty = empty($password);
$emailEmpty = empty($email);
$emailInvalid = !filter_var($email, FILTER_VALIDATE_EMAIL);
if ($passwordEmpty) :
$response->errors[] = "Invalid Password";
$response->fields[] = "password";
endif;
if ($emailEmpty) :
$response->errors[] = "Empty Email";
$response->fields[] = "email";
elseif ($emailInvalid) :
$response->errors[] = "Invalid Email";
$response->fields[] = "email";
endif;
if (empty($response->errors)) :
$response->status = "success";
endif;
}
echo json_encode($response);
exit;

How to set my own upload size of attachment?

I want to set on this PHP code my own size limit of attachment.
I've tried lot of codes but anything isn't working.
Can u help me with it? What working code should I use there?
I want to set maximum size to 2MB, and there should be message ,,Sorry, this attachment is too big (or sth else - it's for check that it's working)".
And how to definite types to attach? For example I want only PNG and JPG to upload. How to do that on my code? And there should be message too, for example - ,,Sorry, you can only attach PNG and JPG files."
NOTE! EVERYTHING IS WORKING RIGHT. I ONLY WANT TO CHANGE UPLOAD SIZE AND MAKE PNG AND JPG FILES :) THANKS!
Here is my PHP code:
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
if(!empty($_POST["send"])) {
require_once ('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->Port = 587;
$mail->Username = "wlasciciel#rubinmc.pl";
$mail->Password = "XXXXXXXXX";
$mail->Mailer = "smtp";
if (isset($_POST["userEmail"])) {
$userEmail = $_POST["userEmail"];
}
if (isset($_POST["userName"])) {
$userName = $_POST["userName"];
}
if (isset($_POST["subject"])) {
$subject = $_POST["subject"];
}
if (isset($_POST["userMessage"])) {
$message = $_POST["userMessage"];
}
if (isset($_POST["NickCheatera"])) {
$NickCheatera = $_POST["NickCheatera"];
}
$mail->SetFrom('wlasciciel#rubinmc.pl', $userName);
$mail->AddReplyTo($userEmail, $userName);
$mail->AddAddress("wlasciciel#rubinmc.pl"); // set recipient email address
$mail->Subject = 'Zgloszenie';
$mail->Body = join('', array(
'Wiadomosc od: ',
$_POST['userName'],
'<br/>',
'E-mail: ',
$_POST['userEmail'],
'<br/>',
'Nick cheatera: ',
$_POST['NickCheatera'],
'<br/>',
'Powod: ',
$_POST['subject'],
'<br/>',
'Dodatkowe informacje: ',
'<br/>',
$_POST['userMessage'],
'<br/>'
));
$mail->WordWrap = 80;
$mail->IsHTML(true);
$mail->SMTPSecure = 'tls';
$mail->Host = 'serwer2092488.home.pl';
if (! empty($_FILES['attachment'])) {
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
// Attaching multiple files with the email
for ($i = 0; $i < $count; $i ++) {
if (! empty($_FILES["attachment"]["name"])) {
$tempFileName = $_FILES["attachment"]["tmp_name"][$i];
$fileName = $_FILES["attachment"]["name"][$i];
$mail->AddAttachment($tempFileName, $fileName);
}
}
}
}
if (! $mail->Send()) {
$message = "Wystąpił problem podczas wysyłania e-maila. Spróbuj ponownie.";
$type = "error";
} else {
$message = "Dziękujemy za zgłoszenie! Odpowiemy do 24 godzin.";
$type = "success";
}
}
HTML code:
<?php
require_once "mail-sending-script.php";
iconv_set_encoding("internal_encoding", "UTF-8");
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" />
<title>RubinMC - zgłoś cheatera</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function validate() {
var valid = true;
$(".info").html("");
var userName = document.forms["mailForm"]["userName"].value;
var userEmail = document.forms["mailForm"]["userEmail"].value;
var NickCheatera = document.forms["mailForm"]["NickCheatera"].value;
var subject = document.forms["mailForm"]["subject"].value;
var userMessage = document.forms["mailForm"]["userMessage"].value;
if (userName == "") {
$("#userName-info").html("(To pole jest wymagane.)");
$("#userName").css('background-color', '#FFFFDF');
valid = false;
}
if (userEmail == "") {
$("#userEmail-info").html("(To pole jest wymagane.)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (!userEmail.match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#userEmail-info").html("(Zły format e-maila.)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (NickCheatera == "") {
$("#NickCheatera-info").html("(To pole jest wymagane.)");
$("#NickCheatera").css('background-color', '#FFFFDF');
valid = false;
}
if (subject == "") {
$("#subject-info").html("(To pole jest wymagane.)");
$("#subject").css('background-color', '#FFFFDF');
valid = false;
}
if (userMessage == "") {
$("#userMessage-info").html("(To pole jest wymagane.)");
$("#userMessage").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
</script>
</head>
<body>
<h1 style="text-align: center">Zgłoś cheatera</h1>
<div class="attachment-form-container">
<form name="mailForm" id="mailForm" method="post" action=""
enctype="multipart/form-data" onsubmit="return validate()">
<div class="input-row">
<label style="padding-top: 20px;">Nick</label> <span
id="userName-info" class="info"></span><br /> <input
type="text" class="input-field" placeholder="Wpisz swój nick..." name="userName"
id="userName" />
</div>
<div class="input-row">
<label>E-mail</label> <span id="userEmail-info"
class="info"></span><br /> <input type="text"
class="input-field" name="userEmail" placeholder="Wpisz adres e-mail..."
id="userEmail" />
</div>
<div class="input-row">
<label>Nick cheatera</label> <span id="NickCheatera-info"
class="info"></span><br /> <input type="text"
class="input-field" name="NickCheatera" placeholder="Wpisz nick cheatera..."
id="NickCheatera" />
</div>
<div class="input-row">
<label for="subject">Powód</label>
<select id="subject" name="subject" class="input-field">
<option disabled selected>Wybierz powód</option>
<option id="Spam">Spam</option>
<option id="X-Ray">X-Ray</option>
<option value="Sales3">Sales2</option>
</select>
</div>
<div class="input-row">
<label>Dodatkowe informacje</label> <span id="userMessage-info"
class="info"></span><br />
<textarea name="userMessage" id="userMessage"
class="input-field" id="userMessage" placeholder="Wpisz dodatkowe informacje..."
cols="60"
rows="6"></textarea><br />
<label>Dodaj załącznik</label>
</div>
<div class="attachment-row">
<input type="file" class="input-field"
name="attachment[]">
</div>
<div>
<input type="submit" name="send" style="position: relative; left: 210px" class="btn-
submit"
value="Wyślij" />
<div id="statusMessage">
<?php
if (! empty($message)) {
?>
<p class='<?php echo $type; ?>Message'><?php echo $message; ?></p>
<?php
}
?>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
var inputPreview = $(".input-preview"),
input = $(".input");
TweenMax.set(input, {
scale: 1.2,
alpha: 0
});
inputPreview.on("click", function(){
var that = $(this);
that.toggleClass("active");
if(that.hasClass("active")){
TweenMax.staggerTo(input, 1.25, {
scale: 1,
alpha: 1,
ease: Elastic.easeOut
}, .1);
}
else {
TweenMax.staggerTo(input, 1, {
scale: 1.2,
alpha: 0,
ease: Elastic.easeOut
}, .1);
}
});
input.on("click", function() {
var tlInput = new TimelineMax({
onComplete: done
});
var that = $(this),
siblings = that.siblings(".input"),
data = that.data("val"),
top = that.css("top");
siblings.removeClass("active");
tlInput.to(siblings, .25, {
alpha: 0
})
.to(that, .25, {
scale: 1.2
})
.to(that, .25, {
top: 0,
})
.set(inputPreview, {
display: "none"
})
.to(that, .25, {
scale: 1,
})
.to(that, .5, {
backgroundColor: "#1D77EF"
})
.set(inputPreview, {
text: data,
display: "block"
})
.to(that, .25, {
alpha: 0
})
function done() {
inputPreview.removeClass("active");
that.css("top", top).addClass("active");
TweenMax.set(input, {
scale: 1.2,
alpha: 0,
backgroundColor: "#fff"
});
}
});
// copy
balapaCop("Select Input Interaction", "rgba(255,255,255,.5)");
});
</script>
</body>
</html>
Try by changing upload_max_filesize in php.ini.

Form should be validate before send a mail using PHPMailer

I'm working with the form using phpmailer. here phpmailer is working fine but before sending a mail I want to validate my form using js.validation is not working how should I validate the form before sending a mail using js. where I have to write a condition for this can anyone help me out I tried in many ways but didn't achieve it.
Below is my code
HTML
<form method="post" action="script.php" id="test" novalidate>
<div class="detail">
<label>name:</label>
<input type="text" name="user_name" data-validation="name" />
</div><!--detail-->
<div class="detail">
<label>Email:</label>
<input type="email" name="user_email" data-validation="email"/>
</div><!--detail-->
<div class="detail">
<label>phone</label>
<input type="number" name="user_phone" data-validation="phone" />
</div><!--detail-->
<div class="detail">
<label></label>
<input type="text" name="user_enquiry" data-validation="message" />
</div><!--detail-->
<div class="detail message">
<label>Message:</label>
<textarea name="user_message" cols="30" rows="15" data-validation="message"></textarea>
</div><!--detail-->
<p><input type="submit" name="send" id="send" value="Send" onclick="formSubmit();" /></p>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
JS:
function formSubmit(){
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
require : true,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
gender: {
error: "gender is required",
},
selectOption: {
error: "this field is required",
required: true
}
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
console.log(element);
element.on('keypress change', function() {
$(error).fadeOut(1000, function() {
console.log(element);
element.removeClass('input-error');
});
});
};
/* Select Option */
this.validate = function() {
var errorCount = 0;
this.form.find("select").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if($(field).val() == "") {
errorCount++;
handleError($(field), validation.error);
}
});
this.form.find("input, textarea").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if(validation !== undefined) {
var re = new RegExp(validation.reg);
if (validation){
if (!re.test($(field).val())){
errorCount++;
handleError($(field), validation.error);
}
}
}
})
/* Radio button */
var radioList = $('input:radio');
var radioNameList = new Array();
var radioUniqueNameList = new Array();
var notCompleted = 0;
for(var i=0; i< radioList.length; i++){
radioNameList.push(radioList[i].name);
}
radioUniqueNameList = jQuery.unique( radioNameList );
console.log(radioUniqueNameList);
for(var i=0; i< radioUniqueNameList.length; i++){
var field = $('#' + radioUniqueNameList[i]);
var type = field.data("validation");
var validation = Elements[type];
if($('input[name='+type+']:checked', '#test').val() == undefined) {
errorCount++;
handleError($(field), validation.error);
}
}
return errorCount == 0;
};
};
/* Submit form*/
$(function(){
$('form#test').on('submit', function (e) {
var NoErrors = new Validator(this).validate();
if(NoErrors == true) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function() {
// AJAX request finished, handle the results and error msg
$('.success_msg').fadeIn().delay(3000).fadeOut();
//$('input[type=text], input[type=number], input[type=email], textarea').val('').removeClass('error');
$('input[type!="submit"], textarea').val('').removeClass('error');
//this.reset();
}
});
}
return false;
})
})
}//formSubmit
PHP:
<?php
include "classes/class.phpmailer.php";
$mail = new PHPMailer; // Passing `true` enables exceptions
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->Port = 587; // TCP port to connect to
$mail->IsHTML(true); // Set email format to HTML
$mail->Username = '***********'; // SMTP username
$mail->Password = '**********'; // SMTP password
$mail->SetFrom('**************');
$msg = 'Name : ' . $_POST["user_name"] . '<br> Email : ' . $_POST["user_email"] . '<br> Phone : ' . $_POST["user_phone"] . '<br> Enquiry : ' . $_POST["user_enquiry"] . '<br> Message : ' . $_POST["user_message"];
$mail->Subject = "subject here";
$mail->Body = $msg;
$mail->AddAddress($_POST["user_email"]);
if(!$mail->Send()){
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Message has been sent with using SMTP.';
}
?>

Validation display name using jQuery remote method

I've tried to added remote method to check display name if is has already exists.
Email validation can check and display messages if email has already exists but Display name validation it does not work. What's wrong with my code?
My code
register.php
<?php require_once 'config.php'; ?>
<?php
if(!empty($_POST)){
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data)$success = USER_REGISTRATION_SUCCESS;
} catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Registration Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Smart Tutorials</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Dispaly Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="Signing Up....">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
register.js
$(document).ready(function(){
$("#register-form").validate({
submitHandler : function(form) {
$('#submit_btn').attr('disabled','disabled');
$('#submit_btn').button('loading');
form.submit();
},
rules : {
name : {
required : true,
name: true,
remote: {
url: "check-name.php",
type: "post",
data: {
name: function() {
return $( "#name" ).val();
}
}
}
},
email : {
required : true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password : {
required : true
},
confirm_password : {
required : true,
equalTo: "#password"
}
},
messages : {
name : {
required : "Please enter name",
remote : "Diaplay name already exists"
},
email : {
required : "Please enter email",
remote : "Email already exists"
},
password : {
required : "Please enter password"
},
confirm_password : {
required : "Please enter confirm password",
equalTo: "Password and confirm password doesn't match"
}
},
errorPlacement : function(error, element) {
$(element).closest('div').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div').removeClass('has-error').addClass('has-success');
$(element).closest('div').find('.help-block').html('');
}
});
});
check-name.php
<?php
require_once 'config.php';
$db = new Cl_DBclass();
if( isset( $_POST['name'] ) && !empty($_POST['name'])){
$name = $_POST['name'];
$query = " SELECT count(name) cnt FROM users where name = '$name' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] > 0){
echo 'false';
}else{
echo 'true';
}
exit;
}
?>
EDIT
check-email.php
<?php
require_once 'config.php';
$db = new Cl_DBclass();
if( isset( $_POST['password'] ) && !empty($_POST['password'])){
$password =md5( trim( $_POST['password'] ) );
$email = $_POST['email'];
if( !empty( $email) && !empty($password) ){
$query = " SELECT count(email) cnt FROM users where password = '$password' and email = '$email' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] == 1){
echo 'true';
}else{
echo 'false';
}
}else{
echo 'false';
}
exit;
}
if( isset( $_POST['email'] ) && !empty($_POST['email'])){
$email = $_POST['email'];
$query = " SELECT count(email) cnt FROM users where email = '$email' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] > 0){
echo 'false';
}else{
echo 'true';
}
exit;
}
?>

How to validate captcha field code?

I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>

Categories