I want to display error messages below the fields in my contact form. But Im not able to do so. Here is my code:-
contact.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" media="screen" href="styles.css" >
<script type="text/javascript" src="my.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("send.php", $("#mycontactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
</head>
<body>
<form id="mycontactform" class="contact_form" action="" method="post" name="contact_form">
<ul>
<li>
<h2>Contact Us</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="John Doe" required />
<small class="errorText"><?php echo $error["name"]; ?></small>
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" id="email" placeholder="john_doe#example.com" required />
<span class="form_hint">Proper format "name#something.com"</span>
<small class="errorText"><?php echo $error["email"]; ?></small>
</li>
<li>
<label for="message">Message:</label>
<textarea name="message" id="message" cols="40" rows="6" required ></textarea>
<small class="errorText"><?php echo $error["message"]; ?></small>
</li>
<li>
<input type="button" class="submit" style="width:70px; text-align:center; height:30px; margin-left:200px; cursor:pointer" value="SEND" id="submit" />
</li><div id="success" style="color:red;"></div>
</form>
</body>
</html>
send.php
<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'babloopuneeth#gmail.com';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: youremail#domain.com' . "\r\n";
$error = array(
"name" => "",
"email" => "",
"message" => ""
);
$email = ( isset( $_POST["email"] ) ) ? trim( $_POST["email"] ) : false;
$name = ( isset( $_POST["name"] ) ) ? trim( $_POST["name"] ) : false;
$message = ( isset( $_POST["message"] ) ) ? trim( $_POST["message"] ) : false;
if ( !$emai ) {
$error["email"] = "Email is required!";
}
if ( !$name ) {
$error["name"] = "Name is required!";
}
if ( !$message ) {
$error["message"] = "Message is required!";
}
else { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}
?>
I tried many other ways but its not working. I just want the error message to be displayed below each field if the field is empty, Plz help me..
Use <br> after each input
$.post : http://api.jquery.com/jQuery.post/
it's jquery AJAX. so you can't display return message with <?php echo $error["name"]; ?> on your form page. You have to use javascript for displaying error messages.
You should use jQuery AJAX in order to retrieve server-side validation. Here is the material.
Just for information, it's better to use jQuery Validation to validate form. Check here for light and thorough examples. You could adapt the code to your case.
Related
i'm coding my very first own website. there is a section where you can enter your name, mail and a message to me.
by clicking "send message" the message should be sent to my personal mail.
the website visitor should receive an alert via a pop-up "message has been sent successfully" or sth like that.
sadly, when clicking "send message" an additional website is opened stating "failed to sent message".
any help is MUCHLY appreciated.
html:
<form action="untitled.php" method="post" target="self">
<p><input class="w3-input w3-border" type="text" id="name" name="name" placeholder="Name" required name="Name"></p>
<p><input class="w3-input w3-border" type="email" id="email" name="email" placeholder="Email" required name="Email"></p>
<p><textarea id="message" type="text" name="message" required placeholder="Message" rows="6" cols="30" ></textarea>
</p>
<button class="w3-button w3-black" type="submit" name="submit" value="submit">
<i class="fa fa-paper-plane"></i> Sende Nachricht
</button>
</p>
</form>
php: code
<?php
$posted = false;
if( $_POST ) {
$posted = true;
$to = 'xx#gmail.com';
$name = $_POST['name'];
$mail_from = $_POST['email'];
$subject = 'Message sent from website';
$message = $_POST['message'];
$header = "From: $name <$mail_from>";
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!') </script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
Welcome to stackoverflow :) i Tested your formula below(you can click run) and seems it works, but you need the untitled.php for it or you can rename it to email.php to make it more specific that email.php is a code only to send email :)
inside email.php(currently untitled.php) please have a look this thread
How to send an email using PHP?
or copy paste this code to email.php(currently untitled.php)
<?php
$to = 'myemail#mail.com'; //your email
$subject = 'from my website - email form';
$message = $_POST['message'];
$headers = 'From: '.$_POST['email']. "\r\n" .
'Reply-To: myemail#mail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
//thank you message
<div>Thanks for your message, I'll answer your email as soon as i can. best regards back »</div>
<form action="untitled.php" method="post" target="self">
<p><input class="w3-input w3-border" type="text" id="name" name="name" placeholder="Name" required name="Name"></p>
<p><input class="w3-input w3-border" type="email" id="email" name="email" placeholder="Email" required name="Email"></p>
<p><textarea id="message" type="text" name="message" required placeholder="Message" rows="6" cols="30" ></textarea>
</p>
<button class="w3-button w3-black" type="submit" name="submit" value="submit">
<i class="fa fa-paper-plane"></i> Sende Nachricht
</button>
</p>
</form>
An example of how to do both methods - traditional form submission and ajax.
<?php
ob_clean();
$payload=array();
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['submit'] ) ){
/* for ajax & standard form submissions */
$args=array(
'name' => FILTER_SANITIZE_STRING,
'email' => FILTER_SANITIZE_EMAIL,
'message' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
/* Have any additional fields been injected into the POST request? */
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) )exit( sprintf( 'unknown parameter "%s"', $field ) );
}
/* Are all the required fields in the POST array? */
foreach( array_keys( $args ) as $field ){
if( !in_array( $field, array_keys( $_POST ) ) )exit( sprintf('Empty or missing parameter "%s"',$field ) );
}
/* assign fields to variables */
extract( $_POST );
/*
check the validity of the email address -
doesn't actually determine if this is a genuine email though
*/
$email = filter_var( $email, FILTER_VALIDATE_EMAIL );
if( $email ){
$to = 'xx#gmail.com';
$from = $email;
$subject = 'Message sent from website';
$headers = sprintf( 'From: %s<%s>', $name, $email );
$status=#mail( $to, $subject, $message, $headers );
$payload['email']=$email;
$payload['status']=$status;
$payload['message']=$message;
$payload['method']='FORM';
}
if( !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest' ){
header('Content-Type: application/json');
$payload['method']='AJAX';
exit( json_encode( $payload ) );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>PHP & Javascript - send email</title>
<script>
const ajax=function(url,params,callback){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
};
xhr.onerror=function(e){
alert(e)
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send( buildparams( params ) );
};
const buildparams=function(p){
if( p && typeof( p )==='object' ){
p=Object.keys( p ).map(function( k ){
return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
}).join('&');
}
return p;
};
document.addEventListener('DOMContentLoaded',function(){
let bttn=document.querySelector('input[type="button"][name="ajax-submit"]');
bttn.addEventListener( 'click', function(e){
let params={
submit:'submit',
name:document.querySelector('input[name="name"]').value,
email:document.querySelector('input[name="email"]').value,
message:document.querySelector('textarea[name="message"]').value
};
let callback=function(r){
let json=JSON.parse( r );
alert( r.status ? 'Yay - message sent!' : 'Boo - message sending failed' );
document.querySelector('form > pre').innerText=r;
};
ajax.call( this, location.href, params, callback )
},false );
},false );
</script>
<style>
form{width:60%;padding:1rem;box-sizing:border-box;margin:2rem auto 0 auto;float:none;border:1px solid black}
input,button{padding:1rem;margin:0.25rem auto}
textarea{padding:1rem;width:100%;resize:none;margin:0.5rem auto}
[type='text'], [type='email'], textarea{width:calc(100% - 2rem);}
[type='button'], button{width:100%;}
pre{width:100%;float:none;margin:auto;color:green;}
</style>
</head>
<body>
<form method='post'>
<input class='w3-input w3-border' type='text' id='name' name='name' placeholder='Name' required name='Name'>
<input class='w3-input w3-border' type='email' id='email' name='email' placeholder='Email' required name='Email'>
<textarea id='message' type='text' name='message' required placeholder='Message' rows='6' cols='30' ></textarea>
<button class='w3-button w3-black' type='submit' name='submit' value='submit'>
<i class='fa fa-paper-plane'>Sende Nachricht</i>
</button>
<input type='button' name='ajax-submit' value='Send Email using ajax' />
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $payload ) ){
printf('<pre>%s</pre>',print_r( $payload,true ) );
} else {
echo '<pre></pre>';
}
?>
</form>
</body>
</html>
I have a pretty basic PHP site and I want a simple spam protection to stop the spam submissions.
I've found one that I like which is a basic 4 character input. Easy to read, small space requirements.
But it says to use a validate.php for the submission action.
My current form's action is to call a the mailer.php (<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">) which is actually included on page load (<?php include 'includes/mailer.php'; ?>).
Can I have two 'actions'? If not, how can I implement the use of this captcha?
When I try adding session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
Just after the opening <?php in mailer.php and then }
else
{
die("Wrong Code Entered");
} just before the closing ?>, the whole website just displays "Wrong code entered" on load.
EDIT:
I'm having trouble understanding where I need to place the various parts of the code and how to tweak it so it works with the existing mailer script.
My unmodified index.php basically consists of the following:
<?php
include 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="section-home">
<header>
<!-- header content -->
<!-- navigation -->
</header>
</section>
<section class="banner full-width-container">
<div class="container">
<!-- other body content -->
<div id="contact">
<div id="contact-form-message"><?php print $output; ?></div>
<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">
<p><span style="color:#f7403a;">Fill in the form below to have an expert contact you</span></p>
<div class="form-left">
<div class="control-group">
<label for="name" class="assistive control-label">Name:</label>
<div class="controls">
<input type="text" name="name" id="name" value="Your Name" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="email" class="assistive control-label">Email: </label>
<div class="controls">
<input type="text" name="email" id="email" value="Your email address" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-left -->
<div class="form-right">
<div class="control-group">
<label for="subject" class="assistive control-label">Subject: </label>
<div class="controls">
<input type="text" name="subject" id="subject" value="Subject" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="telephone" class="assistive control-label">Telephone number </label>
<div class="controls">
<input type="text" name="telephone" id="telephone" value="Your phone number" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-right -->
<div class="control-group">
<label for="message" class="assistive control-label">Message: </label>
<div class="controls">
<textarea name="message" id="message" class="replace-default required type-textarea full-width" rows="5" cols="20">The type of enquiry (e.g. Motor Accident) and a brief message</textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="submit" name="submit" class="btn btn-stacks" value="Send Message"/>
<div id="sending-message"><img src="img/ajax-loader.gif" alt="" /></div>
</div>
</div>
</form>
</div>
</div>
</section>
<footer class="full-width-container" id="footer-section">
<div class="container">
<!-- footer content -->
</div>
</footer>
<!-- ============================================== -->
<script src="js/modernizr-1.7.min.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
And my unmodified mailer.php consist of:
<?php
function cleanInput($input){
$input = trim($input);
if(strlen($input)>0){
$input = htmlspecialchars(stripslashes($input));
}
return $input;
}
$name = '';
$email = '';
$subject = '';
$message = '';
$telephone = '';
$output = '';
if ( isset($_POST['submit']) || isset($_GET['ajax']) == 'true'){
//set up for form fields
$name = cleanInput($_POST['name']);
$email = cleanInput($_POST['email']);
$subject = cleanInput($_POST['subject']);
$telephone = cleanInput($_POST['telephone']);
$message = cleanInput($_POST['message']);
$output ='';
$regex = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";
//do some basic validation
if( $name == '' || $name == 'Full Name' ){ $output = '<li class="alert alert-error">Please enter your name.</li>'; }
if ( !preg_match( $regex, $email ) || $email == 'Email address' ) {
$output .= '<li class="alert alert-error">Please check that your email address is valid</li>';
}
if( $subject == '' || $subject == 'Subject' ){ $output .= '<li class="alert alert-error">Please enter a subject</li>'; }
if( $telephone == '' || $telephone == 'Contact number' ){ $output .= '<li class="alert alert-error">Please enter a contact number</li>'; }
if( $message == '' || $message == 'Your Query' ){ $output .= '<li class="alert alert-error">Please enter a message</li>'; }
//if there are errors, add them to the list here
if ( $output!='' ){
$output = '<div class=""><ul class="unstyled">' . $output . '</ul></div>';
}
//if no errors, try to send the form
else {
/*Put the email address to send to here*/
$to = "email1#domain.com.au";
$headers = 'From: noreply#domain.com.au' . "\r\n";
$headers .= 'Cc: '. $email . "\r\n";
$headers .= 'Bcc: email2#domain.com.au' . ', ' . 'email3#domain.com.au' . ', ' . 'email4#otherdomain.com.au' . "\r\n";
$subject = $subject;
$body = "Name: $name\n\n"
. "Email: $email\n\n"
. "Subject: $subject\n\n"
. "Message: $message"
;
$messageOK = ( mail($to, 'Web Enquiry from the landing page for: ' . $subject, $body, $headers ));
//check if the mail was sent or not
if ( $messageOK ){
$output = '<div class="alert alert-success"><p>Thank you for getting in touch. We will be in contact soon.</p></div>';
}
else {
$output = '<div class="alert alert-error"><p>We could not send your message. Please try again.</p></div>';
}
}
//if ajax is being used, output the message
if ( isset($_GET['ajax']) == 'true' ){
print $output;
}
}
?>
Any information that helps me understand what is required to use this captcha code would be greatly appreciated
You could use a random number generated when form is generated, then passing the value using POST AND $_SESSION, and then compare 2 to see if they match. This is for bot protection/spam.
Would you like an example?
EDIT, didn't fully read the question.
What you want to do is to decide whether the page is loaded as POST request, if is not, then display the form, if is, validate $_POST fields and/or send email.
session_start();
$error = null;
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff`
else
{
$error = "invalid captcha image, please try again!";
}
//the rest of your HTML
//after the recaptcha image HTML
echo isset($error)? $error: '';
This will stop the page from dieing because of the failed captcha, and will produe an error message of 'Invalid captcha image' if the capthc was false.
This question already has answers here:
HTML5 required attribute not working
(2 answers)
Closed 9 years ago.
Hii im doing contact us form without refreshing the page. But after i click on the send button even the fields are empty my required attribute is not working. Please help me
contact.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" media="screen" href="styles.css" >
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("send.php", $("#mycontactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
</head>
<body>
<form id="mycontactform" class="contact_form" action="" method="post" name="contact_form">
<ul>
<li>
<h2>Contact Us</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="John Doe" required />
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" id="email" placeholder="john_doe#example.com" required />
<span class="form_hint">Proper format "name#something.com"</span>
</li>
<li>
<label for="message">Message:</label>
<textarea name="message" id="message" cols="40" rows="6" required ></textarea>
</li>
<li>
<input type="button" class="submit" style="width:70px; text-align:center; height:30px; margin-left:200px; cursor:pointer" value="SEND" id="submit" />
</li><div id="success" style="color:red;"></div>
</form>
</body>
send.php
<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'babloopuneeth#gmail.com';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: youremail#domain.com' . "\r\n";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}else{
echo "Invalid Email, please provide an correct email.";
}
?>
above is my code. please help me. I want required attribute to be worked on clicking the button.
This is just my opinion, but I'd use PHP to check if the input fields are empty or not.
Just having a if statement to see if they are filled out works just fine.
<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if($name=='' || $email=='' || $message=='') { //Make sure all of the fields are not empty
echo "Please fill in all of the fields";
}
else { //If they are filled in, process the rest of the form
$to = 'babloopuneeth#gmail.com';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: youremail#domain.com' . "\r\n";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}else{
echo "Invalid Email, please provide an correct email.";
}
}
?>
I have a contact form that passes the data via jQuery $.post.
JS
$(function () {
$("#contact_form").submit(function (a) {
a.preventDefault();
$.post("<?php echo home_url('/_asset/contact.php'); ?>", {
contact_name : $("#contact_name").val(),
contact_email : $("#contact_email").val(),
contact_subject : $("input:radio[name=subject]:checked").val(),
contact_textarea: $("#contact_textarea").val(),
contact_postid : $("#contact_postid").val(),
}, function (a) {
$("div#response").removeClass("hidden");
$("div#response").delay(1E3).html(a);
});
});
});
contact.php
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST["contact_textarea"];
$contact_postid = $_POST['contact_postid'];
$contact_address = $_SERVER['REMOTE_ADDR'];
if( empty($contact_name) && empty($contact_email) && empty($contact_subject) && empty($contact_message) ) {
die('You must fill out all fields amigo!');
}
// Build that email boy!
if( !empty($contact_postid) ) { $email_id = ' (' . $contact_postid . ')'; }
$email_to = 'email#example.com';
$email_subject = 'Contact Form: ' . $contact_subject . $email_id;
$email_header = 'From: ' . $contact_name . '<' . $contact_email . '>' . "\r\n";
$email_header .= 'Reply-To:' . $contact_email . "\r\n";
$email_header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$email_message = nl2br($contact_message);
// Try sending the email
if(!mail($email_to, $email_subject, $email_message, $email_header)){
$status = 'red';
die('Error sending email.');
} else {
$status = 'green';
die('Email sent!');
}
PHP form
<div class="respond_form">
<form method="post" id="contact_form">
<h2>Let's get contacting!</h2>
<div id="response" class="hidden alert <?php echo $status; ?>"></div>
<div class="line">
<label for="contact_name" title="Please enter your name (required)">Your name <span class="required">*</span></label>
<input type="text" name="contact_name" id="contact_name" tabindex="1" placeholder="John Smith" required="required"/>
</div>
<div class="line">
<label for="contact_email" title="Please enter your email (required)">Your email (so we can contact you) <span class="required">*</span></label>
<input type="email" name="contact_email" id="contact_email" tabindex="2" placeholder="mail#example.com" required="required"/>
</div>
<?php if( isset($_GET['subject']) ) { ?>
<input hidden="hidden" name="subject" type="radio" value="<?php echo $_GET['subject']; ?>" checked="checked">
<?php if( isset($_GET['PostID']) ) { echo '<input hidden="hidden" id="contact_postid" name="postid" type="input" value="' . $_GET['PostID'] . '">'; } ?>
<?php } else { ?>
<div class="line">
<label>What is the message in regards to? <span class="required">*</span></label>
<ul style="list-style:none; margin: 0; padding: 0;">
<label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Advertising"<?php if( $_GET['subject'] == 'advertising' ) { echo ' checked="checked"'; } ?>>Advertising</label>
<label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Contribute an Article"<?php if( $_GET['subject'] == 'contribute' ) { echo ' checked="checked"'; } ?>>Contribute an Article</label>
</ul>
</div>
<?php } ?>
<div class="line">
<label for="contact_textarea" title="Briefly explain your message (required)">Briefly explain your message <span class="required">*</span></label>
<textarea name="contact_textarea" id="contact_textarea" rows="10" tabindex="3" maxlength="500" required="required"></textarea>
</div>
<input type="submit" id="contact_send" name="contact_send" class="button glow" value="Send Message"/>
</form>
</div>
As you can see, I've tried setting a $status in the mail() function but that didn't work. I'm not entirely sure what's going on with the whole thing (found it ages ago and just built around it) but I know the die() message emits into the div#response.
Effectively I was hoping to add a class to the div#response if the email was successful or not.
OH! and incase someone wants to comment on the lack of security, or checking of $_POST data, I've stripped it for here :]
$.post sends the data to contact.php and loads its response.
In your case, the response is text that can be "Error sending email." or "Email sent!" (from what you posted) so you just need to test the value and add the related class.
$(function () {
$("#contact_form").submit(function (a) {
a.preventDefault();
$.post("<?php echo home_url('/_asset/contact.php'); ?>", {
contact_name : $("#contact_name").val(),
contact_email : $("#contact_email").val(),
contact_subject : $("input:radio[name=subject]:checked").val(),
contact_textarea: $("#contact_textarea").val(),
contact_postid : $("#contact_postid").val(),
}, function (a) {
$("div#response").removeClass("hidden").addClass( (a=="Email sent!") ? "email-success" : "email-error" );
$("div#response").delay(1E3).html(a);
});
});
});
if anyone can just go through my code and find possible error, I've tried everything, but I just can't find mistake. My form validates just fine, but when it comes to submit and redirect to next page, it just reloads...
<?php
$your_email ='(i have removed e-mail)';
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';
if(isset($_POST['submit']))
{
$name = $_POST['form-name'];
$visitor_email = $_POST['form-email'];
$subject_email = $_POST['form-subject'];
$user_message = $_POST['form-message'];
$user_id = $_POST['form-id'];
$telephone = $_POST['form-telephone'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Morate popuniti polja ime i e-mail. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Pogresno unet e-mail!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n Verifikacioni kod je pogresno unet!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject = "Nova poruka: $subject_email";
$from = $_POST['form-name'];
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "Posetilac $name je poslao poruku sa web-sajta:\n".
"Ime: $name\n".
"Email: $visitor_email \n".
"Poruka: \n ".
"$user_message\n".
"Broj licne karte: $user_id\n".
"Broj telefona: $telephone\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body, $headers);
header('Location: slanje_uspesno.html');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link href="css/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script language="JavaScript" src="js/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<div id="header">
<div id="container_header">
<div id="logo"></div>
</div>
</div>
<div id="container_kontakt">
<div id="kontakt_email">
<div id="kontakt_middle">
<div id="forma">
<div class="errors_kontakt">
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='form_errorloc' class='err'></div>
</div>
<form id="form" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<ul id="form_list">
<li><label>Vaše ime:</label><input type="text" id="form-name" name="form-name" value='<?php echo htmlentities($name) ?>'/></li>
<li><label>Vaš e-mail:</label><input type="text" id="form-email" name="form-email" value='<?php echo htmlentities($visitor_email) ?>'/></li>
<li><label>Naziv poruke:</label><input type="text" id="form-subject" name="form-subject" /></li>
<li><label>Broj telefona:</label><input type="text" id="form-telephone" name="form-telephone" maxlength="12" /></li>
<li><label>Broj lične karte:</label><input type="text" id="form-id" name="form-id" maxlength="6" /></li>
<li><label>Vaša poruka:</label><textarea name="form-message"><?php echo htmlentities($user_message) ?></textarea></li>
<li><label for="6_letters_code">Verifikacioni broj:</label><img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' > <input id="6_letters_code" class="captcha_code" maxlength="6" name="6_letters_code" type="text" ></li>
<li><label> </label><input type="submit" id="submit" value="POŠALJI" class="submit"></li>
</ul>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("form-name","req","Unesite Vaše ime");
frmvalidator.addValidation("form-email","req","Unesite Vašu e-mail adresu");
frmvalidator.addValidation("form-email","email","Unesite validnu e-mail adresu");
frmvalidator.addValidation("form-id","req","Unesite Vaš broj lične karte");
frmvalidator.addValidation("form-telephone","req","Unesite Vaš broj telefona");
frmvalidator.addValidation("6_letters_code","req","Verifikacioni kod je pogresno unet");
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</div>
</div>
<div id="footer">
</div>
</body>
</html>
You are checking if $_POST['submit'] is ever submitted. Looking at your code, it is never submitted as your submit button doesn't have a name attribute:
<input type="submit" id="submit" value="POŠALJI" class="submit">
It needs to be:
<input type="submit" name="submit" id="submit" value="POŠALJI" class="submit">
There is your problem:
<input type="submit" id="submit" value="POŠALJI" class="submit">
There is no input with the name attribute submit.
Change it to:
<input type="submit" id="submit" name="submit" value="POŠALJI" class="submit">