How can i add recaptcha properly to my html form? - php

I have an AJAX HTML form with validation fields. So my problem is that i'm stuck. I want to embed a recaptcha in my form. I want to produce the following result. If the user completes the recaptcha then the form will be sended. Now if i complete the form and the recaptcha correctly the form is not sended.
HTML
function sendContact() {
var valid;
valid = validateContact();
if(valid) {
jQuery.ajax({
url: "contact_mail.php",
data:'userName='+$("#userName").val()+'&userEmail='+$("#userEmail").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
}
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color','');
$(".info").html('');
if(!$("#userName").val()) {
$("#userName-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userName").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#userEmail").val()) {
$("#userEmail-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userEmail").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#userEmail").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#userEmail-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userEmail").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#subject").val()) {
$("#subject-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#subject").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#content").val()) {
$("#content-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#content").css('background-color','#3E3E3E');
valid = false;
}
return valid;
}
</script>
<div id="frmContact">
<div id="mail-status"></div>
<div>
<span id="userName-info" class="info"></span><br/>
<input type="text" name="userName" id="userName" class="form-control form-dark demoInputBox" placeholder="Όνομα">
</div>
<div>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="form-control form-dark demoInputBox" placeholder="Email">
</div>
<div>
<span id="subject-info" class="info"></span><br/>
<input type="number" name="subject" id="subject" class="form-control form-dark demoInputBox" placeholder="Τηλέφωνο">
</div>
<div>
<span id="content-info" class="info"></span><br/>
<textarea name="content" id="content" class="form-control form-dark demoInputBox" cols="60" rows="6" placeholder="Μήνυμα"></textarea>
</div>
<div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6LcoXZ0UAAAAAMdgKIlchJvizDWic5S7nwr5XD3g"></div>
<button name="submit" class="btn btn-border border-white btnAction" onClick="sendContact();">Αποστολη</button>
</div>
</div>
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// access
$secretKey = '6LcoXZ0UAAAAAF3U4SSfiKPZ7NWyuATN7NFh8fKE';
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
exit;
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
} else {
$to = "vp#digital-media.gr";
$msg = "name:\t$_REQUEST[userName]\n";
$msg .= "email:\t$_REQUEST[userEmail]\n";
$msg .= "tel:\t$_REQUEST[subject]\n";
$msg .= "message:\t$_REQUEST[content]\n";
$success = mail($to, "Mail from our site", $msg, "Content-type: text/plain; charset=UTF-8");
if($success) {
print "<p class='success'>Ευχαριστούμε, το μήνυμα σας έχει σταλθεί. Θα σας απαντήσουμε το συντομότερο.</p>";
} else {
print "<p class='Error'>Υπήρξε ένα σφάλμα, δοκιμάστε αργότερα! </p>";
}
}
?>

Related

When contact form button is clicked, site redirects to a custom post enrty

I've got this wordpress site with a custom post type, called reviews, loop and a contact form on a page. When I click on the submit button on the contact page, reguardless if the form contents matches the regex, it redirects the page to /reviewa/random name
I've removed the "reviews" part of the website and the form works.
What I would like to happen is to have the form send the email, without redirecting the site to /reviews/randomName
$(function() {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
$('#contact-form').submit(function(e) {
$clientName = $("#contactName").val();
var valid = true;
// Remove any confirmation messages
$('p.confirmation').remove();
// Validate all fields that have a class of .required-field
$('.required-field').each(function() {
// Remove error class from all inputs and textareas and delete error messages before checking form again
$(this).removeClass('error').next('p').remove();
if ($(this).val().trim() === '' && $(this).attr('id') != 'email') {
$(this).addClass('error').parent().append('<p class="error">Please enter a ' + $(this).prev().html().toLowerCase() + '</p>');
valid = valid && false;
} else if ($(this).attr('id') === 'email') {
if (!$(this).val().trim().match(re)) {
$(this).addClass('error').parent().append('<p class="error">Please enter a valid email address</p>');
valid = valid && false;
}
}
});
if (valid) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function(data) {
$('#contact-form').before('<p class="confirmation">Thanks ' + $clientName + ', your email was successfully sent. We will be in touch soon.</p>');
_gaq.push(['_trackEvent', 'Contact form', 'Contact form submitted']);
});
}
e.preventDefault();
});
});
<div id="reviews">
<h2>Our reviews</h2>
<div id="slider" class="flex-container">
<div class="flexslider">
<ul class="slides">
<?php $new = new WP_Query('post_type=reviews& posts_per_page=-1');
while ($new->have_posts()) : $new->the_post(); ?>
<li>
<?php echo the_post_thumbnail('portfolio-thumb');?>
<span class="review"> <?php the_content(); ?></span>
<span class="name"> <?php the_title(); ?></span>
</li>
<?php endwhile;?>
</ul>
</div>
</div>
</div>
<div id="contact">
<h2>To contact the instructor, plese enter your details below</h2>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitted'])){
//Check name
if(trim($_POST['contactName']) === '') {
$nameError = true;
$hasError = true;
}else{
$name = trim($_POST['contactName']);
}
//Check company name
if(trim($_POST['companyName']) === '') {
$companyNameError = true;
$companyNameError = true;
}else{
$companyName = trim($_POST['companyName']);
}
//Check address
if(trim($_POST['address']) === '') {
$addressError = true;
$addressError = true;
}else{
$address = trim($_POST['address']);
}
// Check email address exists and is valid
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
}else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+.[A-Z]{2,4}$",trim($_POST['email']))){
$emailError = 'You entered an invalid email address.';
$hasError = true;
}else{
$email = trim($_POST['email']);
}
if(trim($_POST['telNumber']) === '') {
$telError = true;
$hasError = true;
}else{
$telephone = trim($_POST['telNumber']);
}
//Check message
if(trim($_POST['message']) === ''){
$messageError = true;
$hasError = true;
}else{
$message = stripslashes(trim($_POST['message']));
}
//If there is no error, send the email
if(!isset($hasError)){
$emailTo = 'randomEmail#mail.com';
$subject = 'Contact from the Contact Us page';
$body = "Name: $name \n Email: $email \n Telephone: $telephone \n Poxtcode: $address . \n Message:\n$message";
$headers = 'From: randomWebsite.com, <'.$emailTo.'>' . "\n" . "\n" .'Reply-To: ' . $email;
ssmtp($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if($emailSent == true) { ?>
<p class="confirmation">Thanks,
<?php echo $name;?>, your email was successfully sent. We will be in touch soon.</p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contact-form" method="post" novalidate>
<ul>
<li>
<input type="text" placeholder="Name (required)" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])){echo $_POST['contactName'];} ?>" class="required-field" />
<?php if($nameError) { ?>
<p class="error">Please enter your name.</p>
<?php } ?>
</li>
<li>
<input type="text" placeholder="Postcode (required)" name="address" id="address" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" class="required-field" />
<?php if($addressError) { ?>
<p class="error">Please enter your postcode.</p>
<?php } ?>
</li>
<li>
<input type="tel" placeholder="Mobile number (required)" name="telNumber" id="telNumber" value="<?php if(isset($_POST['telNumber'])){echo $_POST['telNumber'];} ?>" />
<?php if($telError) { ?>
<p class="error">Please enter your mobile number.</p>
<?php } ?>
</li>
<li>
<input type="email" placeholder="Email (required)" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" class="required-field" />
<?php if($emailError) { ?>
<p class="error">
<?php echo $emailError;?>
</p>
<?php } ?>
</li>
<li class="textarea">
<textarea name="message" placeholder="Message (required)" id="message" rows="20" cols="30" class="required-field"><?php if(isset($_POST['message'])){echo stripslashes($_POST['message']);} ?></textarea>
<?php if($messageError) { ?>
<p class="error">Please enter a message.</p>
<?php } ?>
</li>
<li>
<input type="hidden" id="submitted" name="submitted" />
<button class="button" ">Send</button>
</li>
</ul>
</form>
</div>

Is there a way to know if my php script for sending form via email worked?

Is there a way i can verify if my php script for sending form to emails worked? I tried running the php website in localhost and tested to submit a message but when I checked my email, nothing has been sent. How do I kno if my form has been received? Is it instantly received when you sent a message from php form via email? How do I know if the email script was wrong or it just didnt send? heres my html:
<div class="container">
<div class="row">
<div class="inquiry2 col-xs-12 col-sm-12 col-md-12 col-lg-12">
<br></br>
<br></br>
<h1>Message Us</h1>
<form action="send.php" id="frmBox" method="post" onsubmit="return formSubmit();">
<div class="form-group">
<label for="InputName">Name*</label>
<input class="form-control" type="text" placeholder="Name" name="customer_name" id="CustomerName">
</div>
<div class="form-group">
<label for="InputEmail">Email Address*</label>
<input class="form-control" type="text" placeholder="email" name="customer_email" id="CustomerEmail">
</div>
<div class="form-group">
<label for="InputPhone">Phone*</label>
<input class="form-control" type="text" placeholder="phone" name="customer_phone" id="CustomerPhone">
</div>
<div class="form-group">
<label for="InputMessage">Message*</label>
<textarea class="form-control" type="text" placeholder="" name="customer_message" id="CustomerMessage"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
</div>
</div>
</div>
<!--SCRIPT-->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function formSubmit(){
$.ajax({
type:'POST',
url:'send.php',
data:$('#frmBox').serialize(),
success:function(response){
$('#success').html(response);
}
});
var form=document.getElementById('frmBox').reset();
return false;
}
</script>
heres the php send:
<?php
$customer_name_error = $customer_email_error = $customer_phone_error = "";
$customer_name = $customer_email = $customer_phone = $customer_message= $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customer_name"])) {
$customer_name_error = "Name is required";
} else {
$customer_name = test_input($_POST["customer_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$customer_name_)) {
$customer_name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["customer_email"])) {
$customer_email_error = "Email is required";
} else {
$customer_email = test_input($_POST["customer_email"]);
if (!filter_var($customer_email, FILTER_VALIDATE_EMAIL)) {
$customer_email_error = "Invalid email format";
}
}
if (empty($_POST["customer_phone"])) {
$customer_phone_error = "Phone is required";
} else {
$customer_phone = test_input($_POST["customer_phone"]);
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$customer_phone)) {
$customer_phone_error = "Invalid phone number";
}
}
if (empty($_POST["customer_message"])) {
$customer_message = "";
} else {
$customer_message = test_input($_POST["customer_message"]);
}
if ($customer_name_error == '' and $customer_email_error == '' and $customer_phone_error == '' ){
$customer_message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$customer_message_body .= "$key: $value\n";
}
$to = 'gorilyawarfare#gmail.com';
$subject = 'Messages';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$customer_name = $customer_email = $customer_phone = $customer_message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

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

Creating PHP Forms with show/hide functionality

I want to create two reports and submit the report data to database by using two functions defined in a class: Here I have two buttons: "Create ES" and "Create RP".
Rightnow, my forms are working fine, I can insert data successfully, but the problem was when I click on submit after filling the form data, the content is hiding and displays the fist div content "cs_content" and again I need to onclick to submit again.
Could anyone give a solution for this.
Requirement :
When I click on "Create CS", I should be able to fill the form and submit data successfully with a message within "cs_content" and any form input errors, the errors should display within "cs_content".
When I click on "Create RP", I should be able to fill the form and submit data successfully with a message within "rp_content" and any form input errors, the errors should display within "rp_content".
home.php
<?php
require 'classes/class.report.php';
$report = new Report($db);
?>
<html>
<head>
<script src="js/jqueryv1.10.2.js"></script>
<script>
$ (document).ready(function ()
{
//$("#cs_content").show();
$('#cs').click(function ()
{
$('#cs_content').fadeIn('slow');
$('#rp_content').hide();
});
$('#rp').click(function ()
{
$('#rp_content').fadeIn('slow');
$('#cs_content').hide();
});
});
</script>
</head>
<body>
<div class="container2">
<div style="margin:0px 0px;padding:3px 217px;overflow:hidden;">
<div id="cs" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE CS"></div>
<div id="rp" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE RP"></div><br>
</div>
<div id="cs_content"> <?php $report->create_cs_report(); ?> </div>
<div id="rp_content" style="display:none;"> <?php $report->create_rp_report(); ?> </div>
</div>
</body>
</html>
class.report.php
<?php
class Report
{
private $db;
public function __construct($database){
$this->db = $database;
}
public function create_cs_report()
{
if (isset($_POST['create_es_report']))
{
$report_name = htmlentities($_POST['report_name']);
$from_address = htmlentities($_POST['from_address']);
$subject = htmlentities($_POST['subject']);
$reply_to = htmlentities($_POST['reply_to']);
if (empty($_POST['report_name']) || empty($_POST['from_address']) || empty($_POST['subject']) || empty($_POST['reply_to']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['report_name']) && empty($_POST['report_name'])) { $errors[] = '<span class="error">Report Name is required</span>'; }
else if (!ctype_alnum($_POST['report_name']))
{ $errors[] = '<span class="error">Report Name: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['from_address']) && empty($_POST['from_address']))
{ $errors[] = '<span class="error">From address is required</span>'; }
else if (filter_var($_POST['from_address'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid From address</span>'; }
if (isset($_POST['subject']) && empty($_POST['subject'])) { $errors[] = '<span class="error">Subject is required</span>'; }
else if (!ctype_alnum($_POST['subject']))
{ $errors[] = '<span class="error">Subject: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['reply_to']) && empty($_POST['reply_to'])) { $errors[] = '<span class="error">Reply To is required</span>'; }
else if (filter_var($_POST['reply_to'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid Reply-To address</span>'; }
}
if (empty($errors) === true)
{
$query = $this->db->prepare("INSERT INTO report(report_name, from_address, subject, reply_to) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $report_name);
$query->bindValue(2, $from_address);
$query->bindValue(3, $subject);
$query->bindValue(4, $reply_to);
try {
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Location:home.php');
echo '<span class="error">Report is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
<div style="font-weight:bold;padding:17px 80px;text-decoration:underline;">Section A</div>
<table class="create_report">
<tr><td><label>Report Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="report_name" required placeholder="Name of the report" value="<?php if(isset($_POST["report_name"])) echo $report_name; ?>" size="30" maxlength="30">
</td></tr>
<tr><td><label>From</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="from_address" required placeholder="From address" value="<?php if(isset($_POST["from_address"])) echo $from_address; ?>" size="30">
</td></tr>
<tr><td><label>Subject</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="subject" required placeholder="Subject" value="<?php if(isset($_POST["subject"])) echo $subject; ?>" size="30">
</td></tr>
<tr><td><label>Reply To</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="reply_to" required placeholder="Reply address" value="<?php if(isset($_POST["reply_to"])) echo $reply_to; ?>" size="30">
</td></tr>
<tr><td><input type="submit" value="create report" style="background:#8AC007;color:#080808;padding:6px;" name="create_es_report"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false) {
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
}
public function create_rp_report()
{
if (isset($_POST['create_rp_report']))
{
$report_name = htmlentities($_POST['report_name']);
$to_address = htmlentities($_POST['to_address']);
$subject = htmlentities($_POST['subject']);
$reply_to = htmlentities($_POST['reply_to']);
if (empty($_POST['report_name']) || empty($_POST['to_address']) || empty($_POST['subject']) || empty($_POST['reply_to']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['report_name']) && empty($_POST['report_name'])) { $errors[] = '<span class="error">Report Name is required</span>'; }
else if (!ctype_alnum($_POST['report_name']))
{ $errors[] = '<span class="error">Report Name: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['to_address']) && empty($_POST['to_address']))
{ $errors[] = '<span class="error">to address is required</span>'; }
else if (filter_var($_POST['to_address'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid to address</span>'; }
if (isset($_POST['subject']) && empty($_POST['subject'])) { $errors[] = '<span class="error">Subject is required</span>'; }
else if (!ctype_alnum($_POST['subject']))
{ $errors[] = '<span class="error">Subject: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['reply_to']) && empty($_POST['reply_to'])) { $errors[] = '<span class="error">Reply To is required</span>'; }
else if (filter_var($_POST['reply_to'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid Reply-To address</span>'; }
}
if (empty($errors) === true)
{
$query = $this->db->prepare("INSERT INTO report(report_name, to_address, subject, reply_to) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $report_name);
$query->bindValue(2, $to_address);
$query->bindValue(3, $subject);
$query->bindValue(4, $reply_to);
try {
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Location:home.php');
echo '<span class="error">Report is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
<div style="font-weight:bold;padding:17px 80px;text-decoration:underline;">Section A</div>
<table class="create_report">
<tr><td><label>Report Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="report_name" required placeholder="Name of the report" value="<?php if(isset($_POST["report_name"])) echo $report_name; ?>" size="30" maxlength="30">
</td></tr>
<tr><td><label>to</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="to_address" required placeholder="to address" value="<?php if(isset($_POST["to_address"])) echo $to_address; ?>" size="30">
</td></tr>
<tr><td><label>Subject</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="subject" required placeholder="Subject" value="<?php if(isset($_POST["subject"])) echo $subject; ?>" size="30">
</td></tr>
<tr><td><label>Reply To</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="reply_to" required placeholder="Reply address" value="<?php if(isset($_POST["reply_to"])) echo $reply_to; ?>" size="30">
</td></tr>
<tr><td><input type="submit" value="create report" style="background:#8AC007;color:#080808;padding:6px;" name="create_rp_report"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false) {
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
}
}//Report CLASS ENDS
First of all
1)
You need javascript code to handle this form validation like:
$("form").submit(function(){
// Your validation code
if(validation not satisfied){
return false;
}
});
2) Check the form wich for is active and make that form active after submit. And your HTML should like this
<body>
<div class="container2">
<div style="margin:0px 0px;padding:3px 217px;overflow:hidden;">
<div id="cs" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE CS"></div>
<div id="rp" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE RP"></div><br>
</div>
<?php $active_form = (is_first_form_checked)?'first_form':'second_form'; ?>
<div id="cs_content" style="<?php echo ($active_form == 'first_form')?'display:none;':''; ?>"> <?php $report->create_cs_report(); ?> </div>
<div id="rp_content" style="<?php echo ($active_form == 'second_form')?'display:none;':''; ?>"> <?php $report->create_rp_report(); ?> </div>
</div>

Ajax to PHP form submission. Keep getting "parsererror"

ajaxSubmit.js:
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#reg').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
login : $('input#login').val(),
pass : $('input#pass').val(),
pass1 : $('input#pass1').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#reg').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text(textStatus).show(500);
$('#reg').show(500);
}
});
return false;
});
});
HTML Form:
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
<br />
</div>
<form id="reg" class="form with-margin" name="reg" method="post" action="">
<br />
<p class="inline-small-label">
<label for="login"><span class="big">Email</span></label>
<input type="text" name="login" id="login" value="">
</p>
<p class="inline-small-label">
<label for="pass"><span class="big">Password</span></label>
<input type="password" name="pass" id="pass" value="">
</p>
<p class="inline-small-label">
<label for="pass1"><span class="big">Password Again</span></label>
<input type="password" name="pass" id="pass1" value="">
</p>
<div align="center"><button type="submit" name="submit" id="submit" >Register</button></div>
</form>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
post.php:
<?php
sleep(3);
$login = $_POST['login'];
$pass = $_POST['pass'];
$pass1 = $_POST['pass1'];
$login = mysql_real_escape_string($login);
$pass = mysql_real_escape_string($pass);
$pass1 = mysql_real_escape_string($pass1);
if (empty($login)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else if (empty($pass)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you password.';
}
else if ($test == false) {
$return['error'] = true;
$return['msg'] = 'Please enter a correct email. This will be verified';
}
else if (empty($pass)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you password twice.';
}
else if ($pass != $pass1) {
$return['error'] = true;
$return['msg'] = 'Your passwords dont match.';
}
else {
$return['error'] = false;
$return['msg'] = 'Thanks! Please check your email for the verification code!';
}
echo json_encode($return);
?>
Any ideas why I keep getting the parsererror?
you have a $test variable else if ($test == false) that is undefined.
I'd suggest that if you are having parse errors through ajax, that you just load up the .php file manually and then php will point you to the line that the error is occurring on.

Categories