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>
Related
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>
I have a simple contact form in a Wordpress website, that needs some protecting.
I gave it two empty fields named "website" and "email" and hid them with CSS (visibility: hidden;). So far, so good.
The problem now is, I just cannot give the PHP commands
if(isset($_POST['website'])) die();
if(isset($_POST['email'])) die();
the proper position in my PHP file. Can you tell me where to position it correctly?
Here is my PHP file:
<?php
if(isset($_POST['website'])) die();
if(isset($_POST['email'])) die();
if(isset($_POST['submitted'])) {
if(trim($_POST['contactVorname']) === '') {
$vornameError = '*';
$hasError = true;
} else {
$vorname = trim($_POST['contactVorname']);
}
if(trim($_POST['contactName']) === '') {
$nameError = '*';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['contactEmail']) === '') {
$emailError = '*';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['contactEmail']))) {
$emailError = '*';
$hasError = true;
} else {
$email = trim($_POST['contactEmail']);
}
if(trim($_POST['unternehmen']) === '') {
/* $unternehmenError = '*';
$hasError = true; */
} else {
$unternehmen = trim($_POST['unternehmen']);
}
if(trim($_POST['ort']) === '') {
/* $ortError = '*';
$hasError = true; */
} else {
$ort = trim($_POST['ort']);
}
if(trim($_POST['telefon']) === '') {
/* $telefonError = '*';
$hasError = true; */
} else {
$telefon = trim($_POST['telefon']);
}
if(trim($_POST['betreff']) === '') {
$betreffError = '*';
$hasError = true;
} else {
$betreff = trim($_POST['betreff']);
}
if(trim($_POST['comments']) === '') {
$commentError = '*';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = 'Kontaktformular | '.$vorname.' '.$name;
$body = "\n.: Kontaktformular-E-Mail :. \n\nName: $vorname $name \nE-Mail: $email \n\nUnternehmen: $unternehmen \nOrt: $ort \nTelefon: $telefon \n\nBetreff: $betreff \n\nNachricht: $comments";
$headers = 'From: '.$vorname.' '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post" id="post-<?php the_ID(); ?>">
<h2 class="gross"><?php the_title(); ?></h2>
<div id="inhalt">
<div class="seitebeitrag">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div><p>Vielen Dank für die Nachricht. Wir melden uns so schnell wie möglich zurück.</p></div>
<?php } else { ?>
<?php the_content(); ?>
<form action="" id="contactForm" method="post">
<div id="kf0"> </div>
<div id="kf1">
<p><label for="contactVorname">Vorname *</label><br />
<input type="text" name="contactVorname" id="contactVorname" value="<?php if(isset($_POST['contactVorname'])) echo $_POST['contactVorname'];?>" maxlength="50" />
<?php if(!empty($vornameError)) { ?>
<span class="fehler"><?=$vornameError;?></span>
<?php } ?></p>
<p><label for="contactName">Nachname *</label><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" maxlength="50" />
<?php if(!empty($nameError)) { ?>
<span class="fehler"><?=$nameError;?></span>
<?php } ?></p>
<p><label for="contactEmail">E-Mail *</label><br />
<input type="text" name="contactEmail" id="contactEmail" value="<?php if(isset($_POST['contactEmail'])) echo $_POST['contactEmail'];?>" maxlength="50" />
<?php if(!empty($emailError)) { ?>
<span class="fehler"><?=$emailError;?></span>
<?php } ?></p>
<p><label for="unternehmen">Unternehmen</label><br />
<input type="text" name="unternehmen" id="unternehmen" value="" maxlength="50" /></p>
<p><label for="ort">Ort</label><br />
<input type="text" name="ort" id="ort" value="" maxlength="50" /></p>
<p><label for="telefon">Telefon</label><br />
<input type="text" name="telefon" id="telefon" value="" maxlength="50" /></p>
<input type="text" id="website" name="website" value="" maxlength="80" /><br />
<input type="text" id="email" name="email" value="" maxlength="80" />
</div>
<div id="kf2">
<p><label for="betreff">Betreff *</label><br />
<input type="text" name="betreff" id="betreff" value="<?php if(isset($_POST['betreff'])) echo $_POST['betreff'];?>" maxlength="50" />
<?php if(!empty($betreffError)) { ?>
<span class="fehler"><?=$betreffError;?></span>
<?php } ?></p>
<p><label for="commentsText">Nachricht *</label><br />
<textarea name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if(!empty($commentError)) { ?>
<span class="fehler"><?=$commentError;?></span>
<?php } ?></p>
<p>* Pflichtfelder</p>
</div>
<div id="kf3">
<input type="submit" value="SENDEN" alt="senden" class="btn" /><br /><input type="hidden" name="submitted" id="submitted" value="true" />
</div>
<div id="kf4">
<?php if(isset($hasError) || isset($captchaError)) { ?>
<div><p class="error fehler">* ungültige oder fehlende Daten</p></div>
<?php } ?></div>
</form>
<?php } ?>
<?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?>
</div>
<?php // edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?>
</article>
<?php // comments_template(); ?>
<?php endwhile; endif; ?>
<?php // get_sidebar(); ?>
<?php get_footer(); ?>
Right now, the form gets totally blocked out, after sending the data, ALTHOUGH the two fields in question are NOT FILLED IN.
$_POST['website'] & $_POST['email'] will always be 'set'. An empty form field still sets the corresponding $_POST entry to an empty string ('') and will always be true to isset. Try using !empty.
if (!empty($_POST['website'])) die();
if (!empty($_POST['email'])) die();
See more here: http://php.net/manual/en/function.empty.php and with a bit more detail here: https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
Be careful using this approach with commonly named fields. They may be automatically filled in by a browser's auto-fill feature meaning you'll be getting false-positives and real users will end up on a blank screen.
Right now I am trying to figure out what is going on with the code. It doesn't make sense why it won't work. When I submit the form I get the error message "comments two" so I know where the problem is but don't understand why its happening. The $newfield variable I made seems to not be storing anything. Any help?
HTML CODE:
<div id="contact-formular">
<div id="message"></div>
<form method="post" action="contact.php" name="contactform" id="contactform">
<div class="one_half element_from_left" style="opacity: 1; left: 0px;">
<input name="name" type="text" id="name" size="30" onfocus="if(this.value == 'Name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Name'; }" value="Name">
<input name="email" type="text" id="email" size="30" onfocus="if(this.value == 'email') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'email'; }" value="email">
<input name="phone" type="text" id="phone" size="30" onfocus="if(this.value == 'phone') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'phone'; }" value="phone">
</div>
<div class="one_half last element_from_right" style="opacity: 1; right: 0px;">
<textarea id="comments" type="text" class="top-text" name="comments" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" value="comments">Architect/ lighting designer/ property developer/ lighting enthusiast/ Will tell later</textarea>
<textarea id="newfield" type="text" class="bottom-text" name="newfield" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" value="newfield">Newfield</textarea>
</div>
<input type="submit" class="send_message" id="submit" value="SEND MESSAGE">
</form>
</div>
PHP CODE:
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$newfield = $_POST['newfield'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Attention! Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message">Comments one</div>';
exit();
} else if(trim($newfield) == '') {
echo '<div class="error_message">Comments two</div>';
exit();
}
Also here is a picture of what it looks like for the error when I submit. If I remove this line of code it works but doesn't capture that area for an email:
else if(trim($newfield) == '') {
echo '<div class="error_message">Comments two</div>';
exit();
}
here is also the full php document https://codeshare.io/GAW7x5
I want to create two reports and submit the report data to database by using two functions within a class: Here I have two submit buttons: "Create ES Report" and "Create RP Report".
(1) When I click on "Create ES Report", create_es_report form should display and be able to fill the data and submit successfully to database and if errors it should display the errors on the same div.
(2) When I click on "Create RP Report", create_rp_report form should display and be able to fill the data and submit successfully to dataabase and if errors it should display the errors on the same div.
Rightnow, When I click on any of the submit buttons, nothing was displaying
index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#es').click(function ()
{
create();
});
});
function create(){
$.ajax({
url: "check.php?proc=create",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
</script>
</head>
<body>
<div class="container2">
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Create ES Report" id="es"></div>
<div id="returnMessage" style="display:none;"></div>
</div>
</body>
</html>
check.php
<?php
require 'includes/config.inc.php';
require 'classes/class.report.php';
$report = new Report($db);
if(isset($_GET['proc']) && !empty($_GET['proc']))
{
$proc = $_GET['proc'];
if($proc == 'create')
{
$report->create_es_report();
$return = array('mes' => 'Created' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
}
else
{
$return = array('mes' => 'The $_GET is empty , check if all parms and ajax function passing to the true file, good luck :).' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
?>
class.report.php
<?php
class Report
{
private $db;
public function __construct($database){
$this->db = $database;
}
//CREATE DATASOURCE REPORT
public function create_es_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>';
}
}
}//Report CLASS ENDS
My guess is that your PHP is failing and the success option is not triggering.
I would suggest adding a console write of data.res in your success option and also add an error option and add a complete option that will write something different to console so you can determine if jquery is failing or if php is failing.
As a side note, I would combine your create_es and create_rp function to 1 since they are identical except for the query string value being passed in ajax. You would then call create_report("es") and create_report("rp") in your click events and your ajax url would be "check.php?proc=" + report, where report is your function param.
You seems don't know how to handle PHP and AJAX as well.
First change the urls E.G:
url: "check.php?proc=create_es",
to
url: "check.php?proc=create",
Look how at check.php the GET works.
And change type: "POST", to type: "GET",
Now to return the error's it's more complicated from just call a php function.
To return the error's you return from the create_es_report error's to the check.php file and return json format to you'r html page, this why i said LEARN ajax first.
Also don't use htmlentities i suggest you to use HTMLPURIFER to santize inputs from malicious inputs.
I'm having all kinds of issues with contact form. When I test on my home server everything runs smoothly. Once I upload it online it doesn't work. First there were problems with headers and now apparently "This web page has a redirect loop".
Here's my code. Please advice me what to do.
Thanks.
<?php
// Title: Contact Form - Dolce Forno GB
// Updated: 5/9/2012
//Validation code
if (!empty($_POST)) {
$errors = array();
//variables
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//All field are required
if (empty($name) === true || empty($email) === true || empty($phone) === true || empty($subject) === true || empty($message) === true ){
$errors[] = 'Please fill in all the fields.';
}
else {
//This regex allows only: a-z,A-Z, space, comma, full stop, apostrophe, dash
if (!preg_match("/^[a-zA-Z\s,.'-]+$/", $name)) {
$errors[] = 'Invalid name.';
/*die ("Invalid name."); */
}
//var_filter php function
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Invalid email address.';
}
//This regex allows only: 0-9, space, dash, brackets, min-max length: 10-15
if (!preg_match("/^[0-9\s]{10,15}$/", $phone)){
$errors[] = 'Invalid phone number.';
}
}
}
if (empty($errors)) {
//send email
mail('info#dolcefornogb.com', 'Contact Form', $subject, 'Message:' . $message,'From: ' . $name . $email . $phone);
header('Location:mail.php?sent');
exit ();
}
print_r($errors);
?>
<DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
}
else {
if (!empty($errors)){
echo '<ul>';
foreach ($errors as $error){
echo '<li>', $error,'</li>';
echo '</ul>';
}
}
?>
<form action="" method="post">
<p> <label for="name">Name
<span class="small">Add your name </span></label>
<input type="text" name="name" id="name"
<?php
if(isset($_POST['name']) === true){
echo 'value="', strip_tags($_POST['name']),'"';
}
?>
>
</p>
<p> <label for="email">E-mail address
<span class="small"> Add your e-mail</span></label>
<input type="text" name="email" id="email"
<?php
if(isset($_POST['email']) === true){
echo 'value="', strip_tags($_POST['email']),'"';
}
?>
>
</p>
<p><label for="phone">Phone<span class="small"> Add your phone number</span></label>
<input type="text" name="phone" id="phone"
<?php
if(isset($_POST['phone']) === true){
echo 'value="', ($_POST['phone']),'"';
}
?>
>
</p>
<p><label for="suject">Subject </label>
<input type="text" name="subject" id="subject"
<?php
if(isset($_POST['subject']) === true){
echo 'value="', strip_tags($_POST['subject']),'"';
}
?>
>
</p>
<p><label for="message">Message:</label>
<textarea name="message" id="messgae" rows="10" cols="50">
<?php
if(isset($_POST['message']) === true){
echo strip_tags($_POST['message']);
}
?></textarea>
</p>
<p><label for="call">Request Phone Call</label>
Yes:<input type="radio" value="Yes" name="call">
No:<input type="radio" value="No" name="call">
</p>
<p class="buttons">
<input type="submit" value="Send"> <input type="reset" value="Clear">
</p>
</form>
<?php
}
?>
Try redirecting to a different page with just the success message in it.
i.e. replace
header('Location:mail.php?sent');
with
header('Location:mail-success.php?sent');
Then get rid of (move to the new page)
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
}
Also try adding 303 status to the header call
http://www.electrictoolbox.com/php-303-redirect/