i need some help with this contact form im trying to fix.
The thing is that it works... kinda. i do get the messages but no success confirmation. the form just fades out a lil' bit and get's stuck i guess but the message does go through.
Any ideas of what im missing here?
<form action="#" id="contact-form">
<div class="input-group name-email">
<div class="input-field">
<input type="text" name="name" id="name" placeholder="Naam/Bedrijf" class="form-control">
</div>
<div class="input-field">
<input type="email" name="email" id="email" placeholder="Email" class="form-control">
</div>
<div class="input-field">
<input type="phone" name="phone" id="phone" placeholder="Telefoon" class="form-control">
</div>
</div>
<div class="input-group">
<textarea name="message" id="message" placeholder="Bericht" class="form-control"></textarea>
</div>
<div class="input-group">
<input type="submit" id="form-submit" class="pull-right" value="Verzenden ">
</div>
</form>
that is my form script
$('#contact-form').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true
}
},
messages: {
name: {
required: "name",
minlength: 2
},
email: {
required: "no email"
},
message: {
required: "no msg",
minlength: 2
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type: "POST",
data: $(form).serialize(),
url: "process.php",
success: function() {
$('#contact-form :input').attr('disabled', 'disabled');
$('#contact-form').fadeTo("slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor', 'default');
$('#success').fadeIn();
});
},
error: function() {
$('#contact-form').fadeTo("slow", 0.15, function() {
$('#error').fadeIn();
});
}
});
}
});
});
</script>
validation
<?php
$to = "";
$from = $_REQUEST['name'];
$subject = $_REQUEST['subject'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"subject"} = "subject";
$fields{"message"} = "message";
$body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$send = mail($to, $subject, $body, $headers);?>
and finally my process.php script. any help would be appreciated. thanks.
<div id="success">
<span>
<p>Your message was sent successfully! I will be in touch as soon as I can.</p>
</span>
</div>
<div id="error">
<span>
<p>Something went wrong, try refreshing and submitting the form again.</p>
</span>
</div>
I have this piece of code as well at the end in the HTML but it just prints with or without submitting
Related
I am having a registration form once user submit the form not clearing the data and it is not displaying the success message as well.here the code which i have written for registration form.
Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('error_messages', 'english');
$this->load->model(VERSION . DOCTOR_MODEL_FOLDER . 'Doctor_model', 'doctors');
$this->load->helper('gmaps');
$this->load->library('locations');
}
public function createAccount() {
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email_id');
$password = $this->input->post('password');
$phone_number = $this->input->post('phone_number_with_ext');
$reg_no = $this->input->post('reg_no');
$regDetails = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email_id' => $email,
'password' => $password,
'reg_no' => $reg_no,
'mobile_no' => $phone_number,
);
$regMessage = $this->doctors->register($regDetails);
//if registration done successfully
if (is_string($regMessage)) {
$data['success'] = true;
$data['response'] = $phone_number;
} else {
//if there is error
$data['success'] = false;
$data['error_msg'] = $regMessage;
}
die(json_encode($data));
}
View:
<div class="form">
<div class="alert" style="display: none;"></div>
<form class="form-validate form-horizontal " id="register_form" method="post" action="" enctype="multipart/form-data">
<div class="form-group ">
<div>
<input class=" form-control" placeholder="First Name" id="first_name" name="first_name" type="text" />
</div>
</div>
<div class="form-group ">
<div>
<input class=" form-control" placeholder="Last Name" id="last_name" name="last_name" type="text" />
</div>
</div>
<div class="form-group ">
<div>
<input class=" form-control" placeholder="Email Address" id="email_id" name="email_id" type="text" />
</div>
</div>
<div class="form-group ">
<div>
<input class="form-control country-code" placeholder="Phone Number" id="phone_number" name="phone_number" type="tel" />
</div>
</div>
<div class="form-group ">
<div>
<input type="text" class="form-control " placeholder="Registration number" id="reg_no" name="reg_no">
</div>
</div>
<div class="form-group ">
<div>
<input class="form-control " placeholder="Password" id="password" name="password" type="password" />
</div>
</div>
<div class="form-group ">
<div>
<input class="form-control " placeholder="Re-enter Password" id="confirm_password" name="confirm_password" type="password" />
</div>
</div>
<div class="form-group">
<div>
<button type="submit" id="btnRegister" class="btn btn-primary btn-lg btn-block">Submit</button>
</div>
</div>
</form>
</div>
JS:
// Submit registration form on button click last_name:{ required: true},
$('form#register_form').validate({
rules: {
first_name: {
required: true,
alpha: true
},
email_id: {
required: true,
email: true
},
phone_number: {
required: true,
number: true,
minlength: 8,
maxlength: 10
},
password: {
required: true,
minlength: 6
},
confirm_password: {
required: true,
minlength: 6,
equalTo: "#password"
},
},
messages: {
first_name: {
required: "Please enter First Name.",
alpha: "Special Characters not allowed."
},
email_id: {
required: "Please enter a email address.",
email: "Please enter a valid email address."
},
phone_number: {
required: "Please enter Phone Number." ,
number: "Please enter Numeric values for Phone Number."
},
password: {
required: "Please provide a password.",
minlength: "Your password must be at least 6 characters long."
},
confirm_password: {
required: "Please provide a password.",
minlength: "Your password must be at least 6 characters long.",
equalTo: "Please enter the same password as above."
},
},
submitHandler: function(form) {
var post_data = $("#register_form").serializeArray();
//var phoneExten = $("ul.country-list li.active").attr('data-dial-code');
var phoneExt = $("#phone_number").intlTelInput("getNumber");
post_data.push({name: "phone_number_with_ext", value: phoneExt});
//console.log(post_data);
$.ajax({
url: "/createAccount",
type: "POST",
data: post_data
}).done(function(res) {
//console.log(res);
var data = $.parseJSON(res);
if( data.success){
$('form#register_form div.form div.alert').removeClass('alert-danger').addClass('alert-success').text('User Created Successfully.').show().delay(2000).fadeOut('slow');
}else{
$('div.form div.alert').addClass('alert-danger').text(data.error_msg.message).show().delay(2000).fadeOut('slow');
$("div.form").scrollTop();
}
});
}
});
Added success message in javascript it is working fine for failure message but not working for success message and once data is submitting it is displaying the data still in form fields.Not getting the data cleared.
Following line work like: first it find from#register_form withing the elements it next find div.form (which isn't inside the form#register_form) then jquery try to find div.alert withing div.form which is not found in your current HTML structure.
div.form is parent node of form#register_form.
$('form#register_form div.form div.alert').removeClass('alert-danger').addClass('alert-success').text('User Created Successfully.').show().delay(2000).fadeOut('slow');
You should change it to:
$('div.alert').removeClass('alert-danger').addClass('alert-success').text('User Created Successfully.').show().delay(2000).fadeOut('slow');
As far as you're submitting form through AJAX you need to clear out all form fields using jquery. You can do it like.
$('form#register_form').trigger("reset");
After end of the code use this line to refresh the page:
redirect('Login/createAccount','refresh');
For Success message:
In Controller Code:
$this->session->set_flashdata('Add', 'Your da`ta added Successfully..');
redirect('Login/createAccount','refresh');
In View page after body:
<?php if($this->session->flashdata('Add')){ ?>
<center><div id="successMessage" class="alert bg-success alert-styled-left">
<button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>
<span class="text-semibold"><?php echo $this->session->flashdata('Add'); ?></span>
</div></center>
<?php } ?>
Javascript code for disable the flash data after particular time:
<script type="text/javascript">
$(document).ready(function(){
$("#successMessage").delay(5000).slideUp(300);
});
</script>
I am new to Web development and I am trying to implement reCaption in my HTML form.
I tried many online tutorials but I was unable to implement it propoerly in my code.
Head :
<script src="https://www.google.com/recaptcha/api.js?render=6LfRQZ4UAAAAAAuMMBQhrBVmyjkVsD"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfRQZ4UAAAAAAuMMBhzvMWVmyjkVsD', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
</script>
Form :
<form id="ajax-contact" method="post" action="mailer.php">
<fieldset>
<div class="form-field">
<input type="text" id="name" name="name" placeholder="Full Name" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input type="email" id="email" name="email" placeholder="Email" value="" required="" aria-required="true" class="full-width"placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="telno" type="text" id="telno" placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="subj" type="text" id="subj" placeholder="Subject" value="" class="full-width">
</div>
<div class="form-field">
<textarea id="message" name="message" placeholder="Leave Message" value="" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
<div class="form-field">
<button id="submit" type="submit" name="submit" class="full-width btn--primary">SEND</button>
<div class="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
mailer.php :
<?php // Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '6LfRQZ4UAAAAAJhdTvqgZyMJB-HO4XL_';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
// Verified - send email
} else {
// Not verified - show form error
}
} ?>
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$telno = trim($_POST["telno"]);
$subj = trim($_POST["subj"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "user#mail.com";
$subject = "New contact from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Telephone Number: $telno\n";
$email_content .= "Subject : $subj\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
app.js :
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-field');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #telno, #subj, #message').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
I want add reCatcha in this form to avoid spammers.
I tried official google docs also but I was unable to implement that properly in my code.
Thanks in advance for any solution.
I'm building a contact form for my site using jQuery validation plugin, ajax call to forward the data to the PHP file, and finally sending the email. Seems like the data is not passed to the php mailer. I'm new to server side technologies, I read a lot but still can't make this working, so please advise me.
the form:
<form class="form-horizontal" role="form" id="contactForm" name="contactForm" method="post">
<div class="form-group">
<label class="col-lg-2 control-label" for="inputName">Name</label>
<div class="col-lg-10">
<input class="form-control" id="inputName" name="inputName" placeholder="Your name" type="text" value="" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputEmail">Email</label>
<div class="col-lg-10">
<input class="form-control" id="inputEmail" name="email" placeholder="your#email.com" type="email" value="" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputMessage">Message</label>
<div class="col-lg-10">
<textarea class="form-control" id="inputMessage" name="inputMessage" placeholder="Message" rows="3" required></textarea>
<button class="btn btn-success pull-right" type="submit" name="submit" id="submit">Send</button>
</div>
</div>
the javascript:
/*validate contact form */
$(function() {
$('#contactForm').validate({
rules: {
inputName: {
required: true,
minlength: 2
},
inputEmail: {
required: true,
email: true
},
inputMessage: {
required: true
}
},
messages: {
name: {
required: "name required",
minlength: "name must be at least 2 characters"
},
email: {
required: "email required"
},
message: {
required: "message required",
minlength: 10
}
},
submitHandler: function(form) {
$('form').ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"index2.php",
success: function() {
alert("message sent");
},
error: function() {
alert("due to an error msg wasnt sent");
}
});
}
});
});
php file:
<?php
if ($_POST["submit"]) {
$name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
$message = $_POST['inputMessage'];
$from = 'Demo Contact Form';
$to = 'example#example.com';
$subject = 'Message from Contact Demo ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
mail($to, $subject, $body, $from);
}
?>
$(form).serialize() doesn't include the submit field (how would it know which submit button you clicked on?), so if ($_POST['submit']) will never succeed. Use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
instead.
Or, if this script is only used for AJAX calls, and not loaded directly by the browser, you can omit that check entirely, as in Glizzweb's answer.
better use checking if:
if (isset($_POST['inputName'])){
//rest part here
}
// and see if the file is in same directory otherwise give relative path.
use this to send form content:
submitHandler: function() {
$('form').ajaxSubmit({
type:"POST",
data: $('#contactForm').serialize(),
url:"submit.php",
success: function() {
alert("message sent");
},
error: function() {
alert("due to an error msg wasnt sent");
}
});
}
In your ajax.php remove $_POST["submit"]
<?php
$name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
$message = $_POST['inputMessage'];
$from = 'Demo Contact Form';
$to = 'example#example.com';
$subject = 'Message from Contact Demo ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
mail($to, $subject, $body, $from);
?>
In ajax page $_POST['submit'] need remove because you post values using "$(form).serialize()" and In you not post value to ajax page. remove if condition "if ($_POST["submit"]) {}" and change like this "if (!empty($_POST["inputName"])) { }"
$name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
.....
....
....
Try this code:
<html>
<head>
<script src="js/jquery-1.11.0.js" type="text/javascript"></script>
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/additional-methods.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#contactForm').submit(function(e){
e.preventDefault();
$('#contactForm').validate({
rules: {
inputName: {
required: true,
minlength: 2
},
inputEmail: {
required: true,
email: true
},
inputMessage: {
required: true
}
},
messages: {
name: {
required: "name value required",
minlength: "name must be at least 2 characters"
},
email: {
required: "email is required"
},
message: {
required: "message is required",
minlength: 10
}
},
submitHandler: function(form) {
alert($('form').html());
$.ajax({
type:"POST",
data: $(form).serialize(),
url:"test1.php",
success: function() {
alert("message sent");
},
error: function() {
alert("due to an error msg wasnt sent");
}
});
}
});
});
});
</script>
</head>
<body>
<form class="form-horizontal" role="form" id="contactForm" name="contactForm" method="post">
<div class="form-group">
<label class="col-lg-2 control-label" for="inputName">Name</label>
<div class="col-lg-10">
<input class="form-control" id="inputName" name="inputName" placeholder="Your name" type="text" value="" >
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputEmail">Email</label>
<div class="col-lg-10">
<input class="form-control" id="inputEmail" name="email" placeholder="your#email.com" type="email" value="" >
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputMessage">Message</label>
<div class="col-lg-10">
<textarea class="form-control" id="inputMessage" name="inputMessage" placeholder="Message" rows="3" ></textarea>
<input class="btn btn-success pull-right" type="submit" name="submit" id="submit" value="Send">
</div>
</div>
</body>
</html>
It is working and showing message sent and ajax call also made. you are doing some mistakes while performing ajax call. as jquery validation plugin does not provide any ajaxsubmit function instead use jquery ajax function as i have used. try it and let me know for further issue.
Change this code to fit your requirement.
I am very new to PHP, so please bear with me here.
It seems like the form goes through, I don't get any errors, but I never receive an email.
Thank you in advance!!
Here is my html
<form class="form-horizontal" role="form" method="POST" id="contact-form" action="contact-form/form.php" style="padding-bottom: 5em;">
<div class="form-group">
<label class="sr-only" for="name">Name</label>
<div class="col-md-12">
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Name">
</div>
</div>
<br>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<div class="col-md-12">
<input type="email" class="form-control" name="email" id="email" placeholder="Enter Email">
</div>
</div>
<br>
<div class="form-group">
<label class="sr-only" for="message">Message</label>
<div class="col-md-12">
<textarea class="form-control" name="message" rows="10"></textarea>
</div>
</div>
<br>
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Here is my php
<?php
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST["save"]) || $_POST["save"] != "contact") {
header("Location: ../index.php"); exit;
}
// get the posted data
$name = $_POST["name"];
$email_address = $_POST["email"];
$message = $_POST["message"];
$headers = 'From: '.$email_address."\r\n" .
'X-Mailer: PHP/' . phpversion();
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Message:\n\n$message";
// send the email
mail ("myEmail", "Someone Wants a Website!", $email_content, $headers);
$to = $_POST['email'];
$subject = 'Thank you for contacting me!';
$msg = 'I have recieved your correspondence and will get back to you as soon as I can. Best regards, Mike Wilcox Designs';
mail($to, $subject, $msg);
header("Location: ../index.php"); exit;
?>
I am also using jquery validate
<script>
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
</script>
So i downloaded a html template, and i cant get the contact form to work..
So here is the contact form:
<form id="contact" action="contact.php" method="get" />
<div class="row-fluid">
<p class="span12">
<label for="name" class="second-color">
Nome</label>
<input type="text" id="name" name="name" class="required second-color span12" maxlength="25" />
</p>
</div>
<div class="row-fluid">
<p class="span12">
<label for="email" class="second-color">
E-mail</label>
<input type="text" id="email" name="email" class="required second-color email span12" maxlength="25" />
</p>
</div>
<div class="row-fluid">
<p class="span12 multi">
<label for="comment" class="second-color">
Mensagem</label>
<textarea id="comment" name="comment" class="required second-color span12"></textarea>
</p>
</div>
ENVIAR MENSAGEM
ENVIAR MENSAGEM
<div id="loadingForm">
<img src="assets/images/loading.gif" alt="loading" />
</div>
</form>
And on the javascript file, i have this piece of code that is related to the form:
/*post operation for contact page*/
$("#contact a").click(function () {
$('#contact #loadingForm').fadeIn('slow');
/*function which validates input with required class in contact page */
var myform = $("#contact").validate({
email: true,
errorPlacement: function (error, element) {
error.appendTo();
}
}).form();
/*myform returns true if form is valid.*/
if (myform) {
var action = $("#contact").attr('action');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
web: $('#web').val(),
message: $('#message').val()
},
function (data) {
d = data;
$('.response').remove();
if (data == 'Message sent!') {
$('#contact a').attr('disabled', '');
$('#contact').append('<span class="success"></p>');
}
else {
$('#contact').append('<span class="response"></span>');
}
});
}
$('#contact #loadingForm').fadeOut('slow');
return false;
});
So now, what do i need to do for the contact work? The template is on ajax, so the form cant reload the page, because if the page is reloaded, the background music will stop.
I have to create the file contact.php, but, if i do that, the page will reloaded when i click on the button, right?
Can anyone help me with this?
Your page won't reload if you call it like you do with Ajax. Just make sure the form doesn't submit.
I would add:
$("#contact a").click(function (event) {
event.preventDefault();
To make sure your page won't reload on click.
Then in the PHP side you can use something like this:
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "emailaddress#here.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Message sent!";
?>