I want to ask about the notification section of a company profile application which I have created
using PHP, AJAX and including PHP send mail function. Somehow it's not working and I don't know what's wrong.
This is my code :
<div class="full black">
<div class="large-12 columns">
<h2 class="white">We are ready.</h2>
<div class='form'>
<form id='contact_form'action="send.php" method='POST'>
<div class="large-4 columns">
<input class='required' name='name' placeholder='NAME' type='text'>
</div>
<div class="large-4 columns">
<input class='required email' name='email' placeholder='EMAIL' type='text'>
</div>
<div class="large-4 columns">
<input class='required' name='subject' placeholder='SUBJECT' type='text'>
</div>
<div class="large-12 columns">
<textarea class='required' name='message' placeholder='MESSAGE'></textarea>
<input id="submit" class='button white boxed contact-button' type='submit' value="Send it">
<p id='thanks' class='hide'>
Thanks for contacting us, we'll be in touch soon!
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<nav>
<a href="#" id='back' class="hide">
<i class="fa fa-close"></i>
</a>
</nav>
if($('form#contact_form').length > 0) {
$('form#contact_form').validate({
messages: { },
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'send.php',
data: $(form).serialize(),
success: function(data) {
if(data.match(/success/)) {
$(form).trigger('reset');
$('#thanks').removeClass('hide').fadeOut(5000);
}
}
});
return false;
}
});
}
and this is my send mail code (I'm using php native) :
$send_to = "toastermedia26#gmail.com";
$send_subject = "Ajax form ";
/*Be careful when editing below this line */
$email = 'vincent#vincentjunior1.xyz';
$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];
function cleanupentries($entry) {
$entry = trim($entry);
$entry = stripslashes($entry);
$entry = htmlspecialchars($entry);
return $entry;
}
$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;
$send_subject .= " - {$f_name}";
$headers = "From: " . $email . "\r\n" .
"Reply-To: " . $f_email . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (!$f_email) {
echo "no email";
exit;
}else if (!$f_name){
echo "no name";
exit;
}else{
if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
$mail = mail($send_to, $send_subject, $message, $headers);
if($mail = true){
json_encode(['ressponses' => 'success']);
}else{
return false;
exit;
}
}
}
I'm really confused. How to make response successfully with my code. Can someone help me.
I have done some changes and tested. It works fine, and try this,
<div class="full black">
<div class="large-12 columns">
<h2 class="white">We are ready.</h2>
<div class='form'>
<form id='contact_form' action="send.php" method='POST'>
<div class="large-4 columns">
<input class='required' name='name' id='name' placeholder='NAME' type='text'>
</div>
<div class="large-4 columns">
<input class='required email' name='email' id='email' placeholder='EMAIL' type='text'>
</div>
<div class="large-4 columns">
<input class='required' name='subject' id='subject' placeholder='SUBJECT' type='text'>
</div>
<div class="large-12 columns">
<textarea class='required' name='message' id ='message' placeholder='MESSAGE'></textarea>
<input id="submit" class='button white boxed contact-button' type='submit' value="Send it">
<p id='thanks' class='hide'>
Thanks for contacting us, we'll be in touch soon!
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<nav>
<a href="#" id='back' class="hide">
<i class="fa fa-close"></i>
</a>
</nav>
In your javaScript,
<script type="text/javascript">
$("#contact_form").unbind('submit').bind('submit', function() {
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var name = $("#name").val();
var email = $("#email").val();
if (name === "") {
$("#name").after('<p class="text-danger">Name field is required</p>');
// $('#name').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#name").find('.text-danger').remove();
// $("#name").closest('.form-group').addClass('has-success');
}
if (email === "") {
$("#name").after('<p class="text-danger">email field is required</p>');
// $('#name').closest('.form-group').addClass('has-error');
} else {
$("#name").find('.text-danger').remove();
// $("#name").closest('.form-group').addClass('has-success');
}
//same as subject and message
if (name && email) {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success == true) {
console.log(response.messages);
// reset the form text
$("#contact_form")[0].reset();
$('#thanks').removeClass('hide').fadeOut(5000);
} // if
} // /success
}); // /ajax
} // if
return false;
}); // /submit form function
</script>
and your send.php file should like this,
<?php
$valid['success'] = array('success' => false, 'messages' => array());
$send_to = "toastermedia26#gmail.com";
$send_subject = "Ajax form ";
/*Be careful when editing below this line */
$email = 'vincent#vincentjunior1.xyz';
$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];
function cleanupentries($entry)
{
$entry = trim($entry);
$entry = stripslashes($entry);
$entry = htmlspecialchars($entry);
return $entry;
}
$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;
$send_subject .= " - {$f_name}";
$headers = "From: " . $email . "\r\n" .
"Reply-To: " . $f_email . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (!$f_email) {
$valid['success'] = false;
$valid['messages'] = "No email";
// exit;
} elseif (!$f_name) {
$valid['success'] = false;
$valid['messages'] = "No name";
// exit;
} else {
if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
$mail = mail($send_to, $send_subject, $message, $headers);
if ($mail = true) {
$valid['success'] = true;
$valid['messages'] = "Successfully sent";
//json_encode(['ressponses' => 'success']);
} else {
$valid['success'] = false;
$valid['messages'] = "Send fail";
}
}
}
echo json_encode($valid);
Think it will be help.
Related
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 2 years ago.
Hello guys i already have a problem with my contact form example when i press send email, email is going but the page wont do anything or even it doesnt show succes message, i want the contact form to be cleared after i press submit button.. website
My html code
<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12">
<div class="contact-form mb50 wow fadeIn">
<h2>Send Message</h2>
<form action="process.php" id="contact-form" method="post">
<div class="form-group" id="name-field">
<div class="form-input">
<input type="text" class="form-control" id="form-name" name="form-name" placeholder="Name.." required>
</div>
</div>
<div class="form-group" id="email-field">
<div class="form-input">
<input type="email" class="form-control" id="form-email" name="form-email" placeholder="Email.." required>
</div>
</div>
<div class="form-group" id="phone-field">
<div class="form-input">
<input type="text" class="form-control" id="form-phone" name="form-phone" placeholder="Phone...">
</div>
</div>
<div class="form-group" id="message-field">
<div class="form-input">
<textarea class="form-control" rows="6" id="form-message" name="form-message" placeholder="Your Message Here..." required></textarea>
</div>
</div>
<div class="form-group">
<button type="submit">Send Message</button>
</div>
My process.php code
<?php
// Configure your Subject Prefix and Recipient here
$subjectPrefix = '[Contact Form Website]';
$emailTo = '<info#mywebsite.com>';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['name']));
$email = stripslashes(trim($_POST['email']));
$phone = stripslashes(trim($_POST['phone']));
$message = stripslashes(trim($_POST['message']));
if (empty($name)) {
$errors['name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email is invalid.';
}
if (empty($phone)) {
$errors['phone'] = 'Phone is required.';
}
if (empty($message)) {
$errors['message'] = 'Message is required.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "$subjectPrefix $subject";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Phone: </strong>'.$phone.'<br />
<strong>Message: </strong>'.nl2br($message).'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . "<$email>" . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
$data['success'] = true;
$data['message'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
My contact-form.js code
(function ($, window, document, undefined) {
'use strict';
var $form = $('#contact-form');
$form.submit(function (e) {
// remove the error class
$('.form-group').removeClass('has-error');
$('.help-block').remove();
// get the form data
var formData = {
'name' : $('input[name="form-name"]').val(),
'email' : $('input[name="form-email"]').val(),
'phone' : $('input[name="form-phone"]').val(),
'message' : $('textarea[name="form-message"]').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('has-error');
$('#name-field').find('.form-input').append('<span class="help-block">' + data.errors.name + '</span>');
}
if (data.errors.email) {
$('#email-field').addClass('has-error');
$('#email-field').find('.form-input').append('<span class="help-block">' + data.errors.email + '</span>');
}
if (data.errors.phone) {
$('#phone-field').addClass('has-error');
$('#phone-field').find('.form-input').append('<span class="help-block">' + data.errors.phone + '</span>');
}
if (data.errors.message) {
$('#message-field').addClass('has-error');
$('#message-field').find('.form-input').append('<span class="help-block">' + data.errors.message + '</span>');
}
} else {
// display success message
$form.html('<div class="alert alert-success">' + data.message + '</div>');
}
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
Cant you simply add location.reload() in your Js at the end of your function when sending succeeds?
try to add a function in js like that
function myFunction() {
location.replace("https://URL")
}
And then onclick="myFunction()"
For my WordPress (v5.5.1) I am using Bootstrap and built a Custom Contact Form in Bootstrap Modal with below HTML (followed this tutorial: https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/).
<form id="contact-form" action="<?php echo get_site_url(); ?>" method="post">
<div class="modal-body">
<?php echo $response; ?>
<div class="form-group">
<input class="form-control my-2" type="text" name="message_name" size="50" placeholder="Your full name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input class="form-control my-2" type="email" name="message_email" size="50" placeholder="Email address" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input class="form-control my-2" type="tel" name="message_tel" size="50" placeholder="Country code, Phone number" value="<?php echo esc_attr($_POST['message_tel']); ?>">
<textarea class="form-control my-2" name="message_text" rows="2" placeholder="Your message" value="<?php echo esc_attr($_POST['message_text']); ?>"></textarea>
<input class="form-control my-2" type="text" name="message_human" placeholder="Human check: Enter 2">
<input type="hidden" name="message_url" value="<?php the_permalink(); ?>">
<input type="hidden" name="message_page" value="<?php the_title(); ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="submitted" value="1">
<button type="submit" value="Submit" class="btn btn-search form-control">Send Enquiry</button>
</div>
Below the function to validate the Forms & show responses while Form submission:
function validateform() {
//response generation function
$response = "";
//function to generate response
function contact_g_form_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
}
//response messages
$not_human = "Enter current year in numbers.";
$missing_content = "Missing something.";
$email_invalid = "Check your Email address.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! We got your enquiry.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$fromEmail = $name . '<' . $email . '>';
$tel = $_POST['message_tel'];
$text = $_POST['message_text'];
$url = $_POST['message_url'];
$page = $_POST['message_page'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = '[General Enquiry] ' . $name . ' | Phone Number:' . $tel;
$headers = 'From: ' . $fromEmail . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$message = '<html><body><h1>New general enquiry from ' . $name . '!</h1>'
. '<p>Email: ' . $email . '</p>'
. '<p>Phone Number: ' . $tel . '</P>'
. '<p>Inquiry: ' . $text . '</P>'
. '<p>From page: <b>' . $page . '</b></P>'
. '<p>Page URL: ' . $url . '</p>'
. '</body></html>';
if (!$human == 0) {
if ($human != 2) {
contact_g_form_response("error", $not_human); //not human!
} else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
contact_g_form_response("error", $email_invalid);
} else { //email is valid
//validate presence of name, phone number
if (empty($name) || empty($tel)) {
contact_g_form_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to, $subject, $message, implode("\r\n", $headers)); //mail to admin - striptags removing formatting
// $sent2 = wp_mail($email, $subject, $body, $headers); //mail to visitor
// if ($sent || $sent2) {
if ($sent) {
contact_g_form_response("success", $message_sent); //message sent!
} else {
contact_g_form_response("error", $message_unsent); //message wasn't sent
}
}
}
}
} else if ($_POST['submitted']) {
contact_g_form_response("error", $missing_content);
}
}
In the earlier versions of WordPress the email was being sent without validation, with v5.5.1 upgrade, the Modal is closing without any validation and the email is also not being sent.
You Just Need To replace this:
<form id="contact-form" action="<?php echo get_site_url();?>" method="post">
With This:
<form id="contact-form" method="post">
Because You are displaying the error on the same page but on click of the submit button the action is taking you to a specific url and that's the reason the validations are not shown.
And This:
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
With This also:
if ($type == "success") {
$response = $message;
echo $response;
} else {
$response = $message;
echo $response;
}
My PHP email form code is working though, but the output after submitting the message is not correct.
After sending a message it is poping an “OK” echo on a blank page (URL www.domain.com/mailform.php), instead of fading out the contact form on the page and fading in the “successful sent” message, without changing the URL.
Where is the bug in the code? :(
HTML
<div class="contact-form-grid">
<form method="post" name="contactForm" id="contactForm" action="sendEmail.php">
<div class="fields-grid">
<div class="styled-input agile-styled-input-top">
<input type="text" for="contactName" id="contactName" name="contactName" required="" />
<label>Dein Name</label></div>
<div class="styled-input agile-styled-input-top">
<input type="text" for="contactTel" name="contactTel" required="" />
<label>Telefon</label></div>
<div class="styled-input">
<input type="email" for="contactEmail" id="contactEmail" name="contactEmail" required="" />
<label>E-Mail</label></div>
<div class="styled-input">
<input type="text" for="contactSubject" id="contactSubject" name="contactSubject" required="" />
<label>Betreff</label></div>
<div class="clearfix"></div>
</div>
<div class="styled-input textarea-grid">
<textarea name="contactMessage" required=""></textarea>
<label>Schreibe hier deine Nachricht!</label></div>
<input type="submit" value="Senden" />
<div id="submit-loader">
<div class="text-loader">Senden...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</form>
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">Ihre Nachricht wurde abgeschickt, danke!
<br /></div>
</div>
PHP
<?php
// Replace this with your own email address
$siteOwnersEmail = 'myemail#gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$tel = trim(stripslashes($_POST['contactTel']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Bitte geben Sie Ihren Namen ein.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Bitte geben Sie eine korrekte E-Mail-Adresse ein.";
}
// Subject
if ($subject == '') { $subject = "Anfrage"; }
// Set Message
$message .= "<strong>" . "Absender: " . "</strong>". $name . "<br />";
$message .= "<strong>" . "Email: " . "</strong>" . $email . "<br /><br />";
$message .= "<strong>" . "Telefon: " . "</strong>" . $tel . "<br /><br />";
$message .= "Nachricht: <br />";
$message .= $contact_message . "<br />";
$message .= "<br /> ----- <br /><i> Gesendet von .... </i></font><br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
if (!$error) {
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Etwas ging schief! Probiere später nochmal."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
JS
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Etwas ging schief! Probiere später nochmal.");
$('#message-warning').fadeIn();
}
});
}
});
I hope someone can help me here :(
Your error is probably in your javascript, is the page refreshing before saying "OK"?
A simpler way to submit a form with ajax is:
$("#form").ajaxForm({
url: "",
beforeSubmit: function() {
},
success: function() {
},
error: function() {
}
});
Did you try this?
I came across a problem with PHP form submission. I'm not able to read the captcha filed value in form submission. Here is the code
HTML
<div class="container">
<h2 class="centertitle">Contact Us</h2>
<div id="message"></div>
<form method="post" action="php/contact.php" name="contactform" id="contactform">
<div class="row">
<div class="col-sm-3">
<input type="text" name="name" placeholder="Name" id="name" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="email" placeholder="Email" id="email" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="phone" placeholder="Phone" id="phone" class="form-control" />
</div>
<div class="col-sm-3">
<div id="captcha">
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<input type="submit" name="send" value="Submit" id="submit" class="sbtn" />
</div>
</div>
</form>
</div><!-- /.container -->
Js Validation
$(document).ready(function() {
//Form Validation
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
//.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
subject: $('#subject').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
Contact.PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$verify = $_POST['verify'];
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 entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) === $_SESSION["security_number"]) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "contact#sreejesh.in";
$e_subject = 'Form Submission.';
$e_body = "You have a new Form Submission." . PHP_EOL . PHP_EOL;
$e_content = "Name: $name,\rPhone: $phone,\rEmail: $email" . PHP_EOL . PHP_EOL;
$e_reply = "";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h4>Email Sent Successfully.</h4>";
echo "<p>Thank you <strong>$name</strong>, for your interest We will contact you shortly.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
For some reason I'm NOT getting value of $captcha
It returns an error says**
Currently the form get submitted without validation.
For Captcha image I use this code -
Captcha Code(IMAGE.PHP)
<?php
session_start();
$img=imagecreatefromjpeg("texture.jpg");
$security_number = empty($_SESSION['security_number']) ? 'error' : $_SESSION['security_number'];
$image_text=$security_number;
$red=rand(100,255);
$green=rand(100,255);
$blue=rand(100,255);
$text_color=imagecolorallocate($img,255-$red,255-$green,255-$blue);
$text=imagettftext($img,16,rand(-10,10),rand(10,30),rand(25,35),$text_color,"fonts/courbd.ttf",$image_text);
header("Content-type:image/jpeg");
header("Content-Disposition:inline ; filename=secure.jpg");
imagejpeg($img);
?>
I'm a beginer in PHP & I'm sitting with this code for the last few hours. PLs help.
Here is a live URL - http://aisther.com/projects/sri/
Do not echo your session variable is it being created by your image.php script and exposing it to the user makes the captcha pointless.
HTML
<form action="contact.php" method="post">
<div id="captcha">
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
</div>
</form>
PHP
session_start();
if($_POST'verify'] == $_SESSION["security_number"]) {
echo 'captcha matched';
} else {
echo 'bad captcha';
}
If you want to use $_POST to read the form data, the form tag needs to look like
<form action='contact.php' method='post'>
Issue solved after adding session_start(); in contact.php
final code(contact.php)
<?php
session_start();
*********************************************************
$verify = $_POST['verify'];
$captcha = $_SESSION["security_number"];
*********************************************************
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) != trim($captcha)) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
*********************************************************
?>
I've got a php / ajax form that works 100% ... but I need a few of the same form on the SAME page. Of course each of the forms will go to a different recipient.
I tried duplicating the form and it seems very complicated! I've tried submitting the duplicated form (with lots of edits to the duplicated form to try get it working) but no success
I don't know if what I am doing is right.
How the form goes is, I have a button when clicked, it toggleslides the div which contains the form... fill in the form, hit submit and an ajax success message pops up saying thank you
HTML FORM:
<body>
<div id="container">
<div id="accommodation_listing_options_box">
<ul id="accommodation_listing_options">
<li>Price Range: <a href="#" class="tooltip" style="cursor:help;" title="Mid-range
Accommodation"><img src="../mid-range-yellow.png" width="28" height="19"
align="absmiddle" style="padding-left:0px;" /></a></li>
<li><a href="#">View
Comments</a> <img src="../comments_bubble_small.png" width="18" height="16"
align="absmiddle" style="padding-left:5px;" /></li>
</ul>
</div>
<div id="quick_enquiry_box">Make Quick Enquiry</div>
<div style="clear:both; width:710px;"></div>
<div style="clear:both;"></div>
<div id="slide_panel">
<div id="contact">
<div id="message"></div>
<form method="post" action="contact.php" name="contactform"
id="contactform">
<div id="my_contact_left">
<label for="name" accesskey="U"><span class="required">*
</span>Name</label><br />
<input name="name" type="text" id="name" size="30" />
<br />
<label for="email" accesskey="E"><span class="required">*
</span>Email</label><br />
<input name="email" type="text" id="email" size="30" />
<br />
<label for="phone" accesskey="P"><span class="required">*
</span>Phone:</label><br />
<input name="phone" type="text" id="phone" size="30" />
<br />
<label for="dayin" accesskey="P">Day in:</label><br />
<input name="dayin" class="datepicker" type="text" id="dayin"
size="30" />
<br />
<label for="dayout" accesskey="P">Day out:</label><br />
<input name="dayout" class="datepicker2" type="text" id="dayout"
size="30" />
</div>
<div id="my_contact_right">
<label for="comments" accesskey="C"><span class="required">*
</span>Your Comments</label><br />
<textarea name="comments" cols="40" rows="3" id="comments"
style="width: 350px; height:100px;"></textarea>
<p><span class="required">*</span>Type the validation code in
below</p>
<div style="width:100px; height:40px; float:left;"><label
for="verify" accesskey="V"> <img src="image.php" alt="Image
verification" border="0"/></label></div>
<div style="width:310px; height:40px; float:right;"><input
name="verify" type="text" id="verify" size="6" value="" style="width: 50px;" />
<input type="submit" style="margin-left:112px;" class="submit"
id="submit" value="Send it!" /></div>
<div style="clear:both; width:410px;"></div>
</div>
<div style="clear:both; width:710px;"></div>
</form>
</div>
<div id="quick_form_wrapper_close"><a href="#"><img src="../close-panel-button.gif"
/></a></div>
</div>
</div>
</body>
If I make a duplicated form, what I need to change in the HTML code is the following:
action="contact.php" name="contactform"
id="contactform"
to:
action="contact2.php" name="contactform2"
id="contactform2"
Is this correct? Anything else I need to change in the HTML?
Moving onto the Javascript:
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$('#submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
dayin: $('#dayin').val(),
dayout: $('#dayout').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message").show().delay(5000).fadeOut();
}
);
});
Do I need to make the field ID's different duplicating a form on the same page?
EG:
$.post(action, {
name2: $('#name2').val(),
email2: $('#email2').val(),
phone2: $('#phone2').val(),
dayin2: $('#dayin2').val(),
dayout2: $('#dayout2').val(),
comments2: $('#comments2').val(),
verify2: $('#verify2').val()
},
Do I need to do any changes to the PHP process form?
Here is the main part of the php process form:
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$dayin = $_POST['dayin'];
$dayout = $_POST['dayout'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits.</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.
</li>';
}
if($error != '') {
echo '<div class="error_message">Attention! Please correct the
errors below and try again.';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
// Advanced Configuration Option.
// i.e. The standard subject will appear as, "You've been contacted by
John Doe."
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Advanced Configuration Option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case
you must be sure to add them here.
$msg = "You have been contacted by $name with regards to Accommodation.
They passed verification and their message is as follows." . PHP_EOL . PHP_EOL;
$msg .= "$comments" . PHP_EOL . PHP_EOL;
$msg .= "You can contact $name via email, $email or via phone $phone." .
PHP_EOL . PHP_EOL;
$msg .= "We want to stay from the $dayin to the $dayout" . PHP_EOL .
PHP_EOL;
$msg .=
"---------------------------------------------------------------------------
-" . PHP_EOL;
if($twitter_active == 1) {
$twitter_msg = $name . " - " . $comments . ". You can contact " .
$name . " via email, " . $email ." or via phone " . $phone . ".";
twittermessage($twitter_user, $twitter_msg, $consumer_key,
$consumer_secret, $token, $secret);
}
$msg = wordwrap( $msg, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<strong>Email Sent Successfully.</strong>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!'; // Dont Edit.
}
}
Thanks in advance! Really appreciate your help because I have tried for hours and I haven't got it right yet!
EDIT:
MY CURRENT JAVASCRIPT CODING:
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$('.submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.post(action, {
name: $('.name').val(),
email: $('.email').val(),
phone: $('.phone').val(),
dayin: $('.dayin').val(),
dayout: $('.dayout').val(),
comments: $('.comments').val(),
verify: $('.verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('.contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('.submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
jQuery(document).ready(function(){
$('.contactform2').submit(function(){
var action = $(this).attr('action');
$('.submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message2").slideUp(750,function() {
$('#message2').hide();
$.post(action, {
name: $('.name').val(),
email: $('.email').val(),
phone: $('.phone').val(),
dayin: $('.dayin').val(),
dayout: $('.dayout').val(),
comments: $('.comments').val(),
verify: $('.verify').val()
},
function(data){
document.getElementById('message2').innerHTML = data;
$('#message2').slideDown('slow');
$('.contactform2 img.loader').fadeOut('fast',function()
{$(this).remove()});
$('.submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message2").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
MY CURRENT JAVASCRIPT CODE:
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$(this).children('.submit').attr('disabled','disabled').after('<img
src="assets/ajax-loader.gif" class="loader" />');
$(this).children("#message").slideUp(750,function() {
$(this).children('#message').hide();
$.post(action, {
name: $(this).children('.name').val(),
email: $(this).children('.email').val(),
phone: $(this).children('.phone').val(),
dayin: $(this).children('.dayin').val(),
dayout: $(this).children('.dayout').val(),
comments: $(this).children('.comments').val(),
verify: $(this).children('.verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$(this).children('#message').slideDown('slow');
$(this).children('.contactform
img.loader').fadeOut('fast',function(){$(this).remove()});
$(this).children('.submit').removeAttr('disabled');
if(data.match('success') != null);
$(this).children("#message").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
Instead of using IDs for the jquery selectors, use classes. You can give all of the forms the same class name and the fields that are the same get the same classes as well.
Then, use those in your jquery:
$('.contactform').submit(function(){
$.post(action, {
name: $(this).children('.name').val(),
It should work for however many instances of the form you have because all of the input fields are referenced by $(this), which is the submitted form, regardless of id or name.
EDIT:
This should work for you. For any number of forms, this is all you would need.
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$('.submit', this).attr('disabled','disabled').after('<img src="assets/ajax-loader.gif" class="loader" />');
$('.message', this).slideUp(750,function() {
$('.message', this).hide();
$.post(action, {
name: $('.name', this).val(),
email: $('.email', this).val(),
phone: $('.phone', this).val(),
dayin: $('.dayin', this).val(),
dayout: $('.dayout', this).val(),
comments: $('.comments', this).val(),
verify: $('.verify', this).val()
},
function(data){
$('.message', this).html(data);
$('.message', this).slideDown('slow');
$('img.loader', this).fadeOut('fast',function() {
$(this).remove();
});
$('.submit', this).removeAttr('disabled');
if(data.match('success') != null);
$('.message', this).show().delay(5000).fadeOut();
});
});
return false;
});
});