How to validate captcha field code? - php

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;
}
}
?>

Related

Why PHP PDO bindParam return null if include jQuery file

On every page I have jQuery modal which contains a contact form and which on every page need sent data to different email address. When a form is submitted I need to display successful response using json_encode. Also on every page I use page identifier as $pages_id=1, $pages_id=2, etc., for identify which form is submitted. However, very important, without jQuery file, complete my PHP code it's executed correctly, all data are successfully inserted into database and in Xdebug I also see that code on every line it's executed successfully. But, if I include jQuery file then in Xdebug the value for $pages_id return null. I exactly think at this line of code:
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();
However, below is my complete PHP code:
<?php
// set error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);
$fname = $tel = $userMail = $userMessage = $email_address_id = "";
$fname_error = $tel_error = $userMail_error = $userMessage_error = "";
$error=false;
//Load the config file
$dbHost = "secret";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "secret";
$dbCharset = "utf8";
$pdo="";
try{
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo "Connection error: " . $e->getMessage();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['submitOwner'])){
$fname = $_POST['fname'];
$tel = $_POST['tel'];
$userMail = $_POST['userMail'];
$userMessage = $_POST['userMessage'];
if(empty($_POST['fname'])){
$error=true;
$fname_error = "Name and surname cannot be empty!";
}else{
$fname = $_POST['fname'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
$fname_error = "Name and surname can only contain letters and spaces!";
}
}
if(empty($_POST['tel'])) {
$tel_error = "Phone number cannot be blank!";
}else{
$tel = $_POST['tel'];
if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
}
}
if(empty($_POST['userMail'])){
$userMail_error = "Email cannot be blank!";
}else{
$userMail = $_POST['userMail'];
if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
$userMail_error = "Email address is incorrect!";
}
}
if(empty($_POST['userMessage'])) {
$userMessage_error = "The content of the message cannot be empty!";
}else{
$userMessage = $_POST['userMessage'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ0-9 ,.!?\'\"]*$/", $userMessage)){
$userMessage_error = "The content of the message cannot be special characters!";
}
}
if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret';
$mail->SMTPAuth = true;
$mail->Username = 'secret';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->setFrom('secret#secret.com');
$mail->Subject = "New message from visit-neum.com";
$mail->isHTML(true);
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=array();
if(is_array($emails_other) && count($emails_other)>0){
foreach($emails_other as $email_other){
//var_dump($email_other['email_address']);
$mail->addAddress($email_other['email_address']);
$body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
$mail->Body = $body_other;
if($mail->send()){
$mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
// Load AJAX
if($error==false){
$information['response'] = "success";
$information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
$jsonData[] = $information;
}
}//end if mail send
else{
$information['response'] = "error";
$information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
$jsonData[]=$information;
}
echo(json_encode($jsonData));
} // end foreach($emails_other as $email_other)
} // end if(is_array($emails_other) && count($emails_other)>0)
} // end if validation
} // end submitOwner
} // end REQUEST METHOD = POST
And below you can see submitHandler for my jQuery file which causes me problem:
submitHandler: function(form){
var formData=jQuery("#contactOwner").serialize();
console.log(formData);
jQuery.ajax({
url: "/inc/FormProcess.php",
type: "post",
dataType: "json",
data: formData,
success:function(jsonData) {
jQuery("#responseOwner").text(jsonData.content);
console.log(jsonData);
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
}); // Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} // end submitHandler
And the page which contains contact form is below:
<?php
include_once './inc/FormProcess.php';
?>
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>
So, I can not figure out what is the problem and why $pages_id return null when include jQuery file. Also, I was forget to mention that code inside line if(is_array($emails_other) && count($emails_other)>0){ return number 0, so complete seguent code isn't executed, but of course this is normal, because $pages_id is null. However, I hope that somebody understand what is the problem and so, thanks in advance for any kind of help that you can give me.
page_id is null in your script because you dont set it in the script.
So why not just adding an hidden input field in your froms with the page id and then in your PHP code
$page_id = $_POST['pageId'];
i think you did not understood ajax correclty. if you post your data to /inc/FormProcess.php it is not like an include before, where you could create variables first and then include it. AJax is like a sub call to the script. it is like if you would open ONLY this scrirpt provided in URL. so at this point you dont have your variables.
you need to get the variables or send your ajax request NOT to /inc/FormProcess.php but to the script where you define the variable
All you have to do is add input type hidden at the end of the form, so my correct form should look like this:
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form ajax' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Vaše ime i prezime..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Vaš broj telefona..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Vaš e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Vaša poruka..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="hidden" name="pages_id" value="<?=$pages_id?>">
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="POŠALJI"/>
</form>

Send multiple contact form from one page via AJAX

I have 3 contact form in one page ( Header, Body, Footer ). The code works correctly if sent from one form. I want to use one AJAX request for all forms. That is, when you click on the submit button, so that the code checks if this form then send data to php. How can i do it right? I use the hasClass () method of jquery, but I have errors in the console
HTML:
Footer Form
<form id="contact-form1" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="name" placeholder="Name">
<input type="text" class="simple-input" id="email" placeholder="Email address">
<textarea class="quession-input" id="msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" class="checked-checkbox" name="myCheckboxes[]" id="box1" checked="checked" value="true" />
<label for="box1" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn submit1"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
Another Form
<form id="contact-form" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="hy_name" placeholder="Name">
<input type="text" class="simple-input" id="hy_email" placeholder="Email address">
<textarea class="quession-input" id="hy_msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" id="box3" class="checked-checkbox" checked="checked" />
<label for="box3" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn hy-submit submit2"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
jQuery:
jQuery('#submit').on('click', function(e) {
e.preventDefault();
if(e.hasClass('submit1')) {
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var msg = jQuery('#msg').val();
var subj = jQuery('#subj').val();
var data = "action=send_email&name=" + name + "&email=" + email + "&msg=" + msg + "&subj=" + subj + "&myCheckboxes=" + choice,
} elseif (e.hasClass('submit2')) {
var hy_name = jQuery('#hy_name').val();
var hy_email = jQuery('#hy_email').val();
var hy_msg = jQuery('#hy_msg').val();
var data = "action=send_email&name=" + hy_name + "&email=" + hy_email + "&msg=" + hy_msg + "&myCheckboxes=" + choice,
}
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
var chkElem = document.getElementsByName("myCheckboxes[]");
var choice ="";
for(var i=0; i< chkElem.length; i++)
{
if(chkElem[i].checked)
choice = choice + chkElem[i].value;
}
jQuery.ajax({
type: "post",
url: "/wp-admin/admin-ajax.php",
data: data;
success: function (response) {
jQuery('#contact-form input').val('');
jQuery('#contact-form textarea').val('');
jQuery('.submit').text('Done!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
PHP:
add_action('wp_ajax_nopriv_send_email', 'send_email');
add_action('wp_ajax_send_email', 'send_email');
function send_email() {
$checkbox = $_POST['myCheckboxes'];
if (isset($checkbox)) {
echo $checkbox;
}
$headers = 'Content-Type: text/html; charset="utf-8"';
$name = $_POST['name'];
$hy_name = $_POST['hy_name'];
$from = 'contact#xelon.ch';
$to = 'yaver.mammadov#gmail.com';
$email = $_POST['email'];
$hy_email = $_POST['hy_email'];
$msg = $_POST['msg'];
$hy_msg = $_POST['hy_msg'];
$subject = 'Footer form: ' . $_POST['email'];
$message .= (!empty($name)) ? '<p><strong>User Name</strong> : ' . $name .' </p>' : '';
$message .= (!empty($email)) ? '<p><strong>User Email</strong> : '. $email .'</p>' : '';
$message .= (!empty($msg)) ? '<p><strong>User Message</strong> : '.$msg .'</p>' : '';
$message .= (!empty($checkbox)) ? '<p><strong>Checkboxs</strong> : '.$checkbox .'</p>' : '';
$message .= '</body></html>';
echo mail($to, $subject, $message, $headers);
return $msg;
die();
}
You can use method serialize(), and use a class to identifique buttons submit. Using two identical ids on one page is not good practice.
If you use the class .submit per example in each button submit:
$('.submit').on('click', function(e) {
e.preventDefault();
var data = $(this).closest('form').serialize();
[...]
}

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.';
}
?>

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;
}
?>
<!--

PHP/Ajax contact form clear input fields only if success

I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!
Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});

Categories