I am newer for codeigniter. I have an one contact form with fields of stream, name, email, contact. But I have an problem with form data are not send to admin email. When i tried to submit the data on contact form page source will alert but i have given other alert data.
I have tried following code,
$('#interiorid').submit(function (e) {
e.preventDefault();
var interiorstream = $('#interiorstream').val();
var interiorname = $('#interiorname').val();
var interiormobile = $('#interiormobile').val();
var interioremail = $('#interioremail').val();
var mobileVarify = /[0-9]/.test(interiormobile);
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var dataString = 'interiorstream =' + interiorstream + '&interiorname =' + interiorname + '&interiormobile =' + interiormobile + '&interioremail =' + interioremail;
alert(interiorstream);
if (interiorstream == "0") {
alert('Please select Stream');
}
else {
if (interiorname.length > 2) {
if (mobileVarify == true && interiormobile.length == 10) {
if (regex.test(interioremail) == true) {
$.ajax({
url: 'interior_email',
type: 'post',
data: dataString,
success: function (msg, status) {
alert(status);
alert(msg);
$("#interiorid")[0].reset();
window.location.href = "/contact/thank-you";
}
});
}
else {
alert('Invalid Email');
}
}
else {
alert('Invalid Number');
}
}
else {
alert('Please enter name');
}
}
});
<!--- View ---->
<form id="interiorid">
<div class="form-div">
<select value="" id="interiorstream" >
<option value="0">Select a Stream</option>
<option value="Interior Designing">Interior Designing</option>
<option value="Fashion Designing">Fashion Designing</option>
</select>
</div>
<div class="form-div">
<input type="text" placeholder="Name" id="interiorname">
</div>
<div class="form-div">
<input type="text" placeholder="Phone" id="interiormobile">
</div>
<div class="form-div">
<input type="text" placeholder="Email" id="interioremail">
</div>
<div class="form-div">
<input type="submit" value="submit">
</div>
</form>
<!----Controller ---->
<?php
class Home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
$this->load->helper(array('url'));
}
function index() {
$this->load->view('templates/header');
$this->load->view('home');
$this->load->view('templates/footer');
$this->load->helper('form');
$this->load->view('interior/interior-intro');
}
function interior_email()
{
if (!isset($_POST['e-mail'])){
//redirect if no parameter e-mail
redirect(base_url());
}else{
$interiorstream = $this->input->post('interiorstream');
$interiorname = $this->input->post('interiorname');
$interiorphone = $this->input->post('interiorphone');
$interioremail = $this->input->post('interioremail');
$message = 'Hello Admin, This mail received from Interior design page contact form.<br/><br/>
Stream:' . $interiorstream . '<br/><br/>
Name :' . $interiorname . '<br/><br/>
Contact :' . $interiorphone . '<br><br>
Email :' . $interioremail;
$headers1 = "MIME-Version: 1.0\r\n";
$headers1 .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers1 .= "To:";
$headers1 .= "example.com <info#example.com>";
$headers1 .= "\r\n";
$headers1 .= 'From: INIFD : info#example.com' . "\r\n";
$headers1 .= "\r\n";
$subject = "Enquiry From example.com Web";
$email = 'admin#example.com';
if (mail($email, $subject, $message, $headers1)) {
echo 'mail has been sent';
} else {
echo 'mail sending failed';
}
}
}
}
?>
wrong popup like this:
So please help me.
If you are running on a localhost, it is near impossible to send emails. You can check this is if you really want to send Check this post out or try PHPMailer
Related
Hi i have been trying for a good 2 hours to get this dropdown menu to get the selected result to go to email through post method im new to php and i think i could just do with abit of guidance ill post html php js code below.i have tried many ways this isnt my only edit ive literally tried everything i just need a little help
html
<div class="col-lg-3">
<div class="form-group mt-2">
<div class="dropdown" >
<select name="vehicles" id="vehicles" class="ddstyle">
<option value="motor" selected>Motorcycle</option>
<option value="Car">Car</option>
<option value="Small">Small Van</option>
<option value="Opel">Opel</option>
<option value="Midi">Midi Van</option>
<option value="SWB">SWB up to 2.4m</option>
<option value="MWB3">MWB up to 3m</option>
<option value="LWB4">LWB up to 4m</option>
<option value="XLWB4">XLWB 4m+</option>
<option value="Luton">Luton</option>
<option value="T5">7.5T</option>
</select>
</div>
</div>
</div>
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'];
$comments = $_POST['comments'];
$dod = $_POST['dod'];
$yourname = $_POST['yourname'];
$tel = $_POST['tel'];
$caddy = $_POST['caddy'];
$cpost = $_POST['cpost'];
$daddy = $_POST['daddy'];
$dpost = $_POST['dpost'];
$dofd = $_POST['dofd'];
$Car = $_POST['Car'];
$Small = $_POST['Small'];
$Opel = $_POST['Opel'];
$Midi = $_POST['Midi'];
$MWB = $_POST['MWB'];
$MWB3 = $_POST['MWB3'];
$LWB4 = $_POST['LWB4'];
$XLWB4 = $_POST['XLWB4'];
$Luton = $_POST['Luton'];
$T5 = $_POST['T5'];
//*$vehicles = $_POST['$vehicles'];**/
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
if(isset($_POST['vehicles']) && $_POST['vehicles']=='motor') echo $value;
if(trim($name) == '') {
echo '<div class="error_msg">You must enter your company name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_msg">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_msg">You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($dod) == '') {
echo '<div class="error_msg">Please enter your collection date.</div>';
exit();
}
if(trim($dofd) == '') {
echo '<div class="error_msg">Please enter your drop off deadline.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#example.net";
$address = "admin#ready2gologistics.co.uk";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = ' ' . $name . ' has a possible job!';
// 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.
$e_body = "$name wants a quote details are listed below." . PHP_EOL . PHP_EOL;
$e_content =
"
Company: $name
Name of Person: $yourname
Contacts email: $email
Contacts Telephone Number: $tel
Desired Collection Date: $dod
Drop Off Deadline: $dofd
Collection Address: $caddy
Collection Post Code: $cpost
Destination Address: $daddy
Destination Post Code: $dpost
Addtional Information: $comments
test: $value
" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$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_msg'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your quote has been submitted to us. To see how we use your information check out our <a href='PrivacyPolicy.html".$link_address."'>Privacy Policy</a></p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
JavaScript
//Contact
$('#working_form').submit(function() {
var action = $(this).attr('action');
$("#message").slideUp(750, function() {
$('#message').hide();
$('#submit')
.before('<img src="" class="gif_loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
dod: $('#dod').val(),
dofd: $('#dofd').val(),
yourname: $('#yourname').val(),
cpost: $('#cpost').val(),
caddy: $('#caddy').val(),
tel: $('#tel').val(),
daddy: $('#daddy').val(),
dpost: $('#dpost').val(),
vehicles: $('#vehicles').val(),
value: $('#value').val(),
},
function(data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.gif_loader').fadeOut('slow', function() {
$(this).remove()
});
$('#submit').removeAttr('disabled');
if (data.match('success') != null) $('#cform').slideUp('slow');
}
);
});
return false;
});
In $.post request pass send value
$.post(action, {
...other data
value: $('#value').val(),
send: $('#send').val(),
}
Because your $value vehicle data is depended on if(isset($_POST['send'])) check
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
I'm just a beginner and trying to implement ajax contact form with php mailing script. But when I click on Submit nothing happens and nothing appears.
Below is my codes.
HTML
<form id="contactform" class="contact-form text-center" role="form">
<!-- IF MAIL SENT SUCCESSFULLY -->
<h6 class="success">
<span class="olored-text icon_check"></span> Your message has been sent successfully.</h6>
<!-- IF MAIL SENDING UNSUCCESSFULL -->
<h6 class="error">
<span class="colored-text icon_error-circle_alt"></span> E-mail must be valid.</h6>
<input id="cf-name" type="text" name="cf-name" placeholder="Your Name">
<input id="cf-email" type="email" name="cf-email" placeholder="Your Email">
<input id="cf-address" type="text" rows="7" name="cf-address" placeholder="Your Home Address">
<input id="cf-phone" type="text" rows="7" name="cf-phone" placeholder="Your Phone Number">
<input type="submit" class="button alt" value="Submit" id="submit" name="submit" data-style="expand-left"/>
</form>
Javascript
// Function for email address validation
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
/* =================================
CONTACT FORM
=================================== */
$("#contactform").submit(function (e) {
e.preventDefault();
var name = $("#cf-name").val();
var email = $("#cf-email").val();
var address = $("#cf-address").val();
var message = $("#cf-phone").val();
var dataString = 'name=' + name + '&email=' + email + '&address=' + address + '&phone=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
}
if (isValidEmail(email) && (message.length > 1) && (address.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function () {
$('.success').fadeIn(1000);
$('.error').fadeOut(500);
}
});
}
else {
$('.error').fadeIn(1000);
$('.success').fadeOut(500);
}
return false;
});
PHP
<?php
// Get values from jquery
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$to = "name#email.com";
$subject = "New Email Subscriber";
$message = " Name: " . $name . "\r\n\r\n Email: " . $email . "\r\n\r\n Address: " . $address . "\r\n\r\n Phone: " . $phone;
$from = "ContactForm";
$headers = "From:" . $from . "\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n";
if (#mail($to, $subject, $message, $headers)) {
echo "success";
} else {
echo "invalid";
}
Can someone please fix this code? I don't what's wrong with it.
Thanks in advance.
It may have nothing to do with Ajax but the php native mail function; I recommend use something like phpMailer since they are much more reliable than native function.
I found the following codes for processing a contact form and would like to add error handling and exceptions to them.
HTML Form looks like:
<div class="contact-form">
<form id="contact-form" action="sendmail.php" method="post" title="Contact Form" role="form">
<div class="col-sm-6">
<div class="form-group">
<label for="contact-name">Name</label>
<input type="text" name="name" placeholder="Enter your name..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-email">Email</label>
<input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email">
</div>
<div class="form-group">
<label for="contact-subject bold">Subject</label>
<input type="text" name="subject" placeholder="Your subject..." class="contact-subject" id="contact-subject">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="contact-message">Message</label>
<textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message"></textarea>
</div>
</div>
<div class="col-sm-12 text-center">
<button type="submit" class="btn btn-default sketchFlowPrint" id="submit">Send</button>
</div>
</form>
</div>
sendmail.php looks like:
<?php
// Email address verification
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($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$subject = addslashes(trim($_POST['subject']));
$message = addslashes(trim($_POST['message']));
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail . "\r\n";
mail($emailTo, $subject . ' (Example - Website)', $message, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
jquery script looks like:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Name');
emailLabel.html('Email');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});
The code works very nice excepts for TWO things:
I receive the email but the clients email address is not displayed anywhere on my email and I cannot reply to the client, I tried messing around with the headers section but couldn't get it right (please help me fix this).
I want the form to let the user know if the form was not submitted. For this I added this code to the jquery script after the last "if" function:
else {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('Something went wrong! Please refresh page and try again.');
});
}.
I would like to add exceptions to this. I want this "else" function I added to only execute if there is something wrong with the anything else except for when the user did not fill all the required fields (if the user did not fill in the required fields the form must display "Please enter you name." or "Please insert a valid email address." or "Please enter your message." on top of the input fields depending on which field was not filled). Hope this makes sense.
in your php, you should define another couple of variables
1. $my_email = "info#example.com"; //senders email
2. $subject = "Query from My Domain"; //a subject line
and then use
mail($_REQUEST['email'],$subject,$message,$headers,"-f{$my_email}");
where
$headers = "From: " . $my_email;
actually i usually use
$headers = "From: " . $my_email;
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
i don't quite why you have the receiver's email in the php; these values should be posted from your form
e.g. $field_order_keys = array('name','email','comment');
and then requested using $_REQUEST
this will fix the sender's email problem
i have created a plunker of a generic form of my contact php script that i generally use. It has gibberish and field-checking etc in it. Perhaps you will find it useful (the link doesn't land on it, it's the contactconfirm.php above it)
I have some trouble cleaning and making my contact form working.
I'm using a template which had a captcha validation and I don't want it. There was also a "website input that I delete.
I'm a newbie in php so I don't really know what I have to remove and I don't want to start a new php/js files
My contact-send.php file is in a php folder. So I assume the action call in the html is good.
I have two other files in there ( captcha_page.php and image.php but I won't use here, will delete it, so I don't post code )
<form class="contact-form" method="post" action="php/contact-send.php">
<p class="input-block">
<input type="text" name="name" id="name" placeholder="Name *" />
</p>
<p class="input-block">
<input type="email" name="email" id="email" placeholder="Email *" />
</p>
<p class="input-block">
<textarea name="message" id="message" placeholder="Message *"></textarea>
</p>
<p class="input-block">
<button class="button turquoise submit" type="submit" id="submit"><i class="icon-paper-plane"></i></button>
</p>
</form><!--/ .contact-form-->
<?php
if (isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == "contact_form_request") {
$ourMail = "xxx.xxxx#gmail.com";
$required_fields = array("name", "email", "message");
$pre_messagebody_info = "";
$errors = array();
$data = array();
parse_str($_REQUEST['values'], $data);
//check for required and assemble message
if (!empty($data)) {
foreach ($data as $key => $value) {
$name = strtolower(trim($key));
if (in_array($name, $required_fields)) {
if (empty($value)) {
if ($name == "name") {
$errors[$name] = "Please enter your Name before sending the message";
}
if ($name == "message") {
$errors[$name] = "Please enter your message ";
}
if ($name == "email") {
if (!isValidEmail($value)) {
$errors[$name] = "Please enter correct Email address";
}
}
}
}
}
}
session_start();
$verify = $_SESSION['verify'];
if ($verify != md5($data['verify'])) {
$errors["verify"] = "Please enter correctly captcha";
}
$result = array (
"is_errors" => 0,
"info" => ""
);
if (!empty($errors)) {
$result['is_errors'] = 1;
$result['info'] = $errors;
echo json_encode($result);
exit;
}
$pre_messagebody_info .= "<strong>Name</strong>" . ": " . $data['name'] . "<br />";
$pre_messagebody_info .= "<strong>E-mail</strong>" . ": " . $data['email'] . "<br />";
$pre_messagebody_info .= "<strong>Website</strong>" . ": " . $data['website'] . "<br />";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers.= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers.= "From: " . $data['email'] . "\r\n";
$after_message = "\r\n<br />--------------------------------------------------------------------------------------------------\r\n<br /> This mail was sent via contact form";
if (mail($ourMail, "Email from contact form", $pre_messagebody_info .="<strong>Message</strong>" . ": " . nl2br($data['message']) . $after_message, $headers)) {
$result["info"] = "success";
} else {
$result["info"] = "server_fail";
}
echo json_encode($result);
exit;
}
}
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
?>
if ($('.contact-form').length) {
var $form = $('.contact-form'),
$loader = '<span>Loader...</span>';
$form.append('<div class="hide contact-form-responce" />');
$form.each(function () {
var $this = $(this),
$response = $('.contact-form-responce', $this).append('<p></p>');
$this.submit(function () {
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $this.serialize()
};
//send data to server
$.post("php/contact-send.php", data, function (response) {
$('.wrong-data', $this).removeClass("wrong-data");
$response.find('span').remove();
response = $.parseJSON(response);
if (response.is_errors) {
var p = $response.find('p');
p.removeClass().addClass("error");
$.each(response.info, function (input_name, input_label) {
$("[name=" + input_name + "]", $this).addClass("wrong-data");
p.append(input_label + '</br>');
});
$response.show(300);
} else {
$response.find('p').removeClass().addClass('success');
if (response.info === 'success') {
$response.find('p').append('Your email has been sent!');
$this.find('input, textarea, select').val('').attr('checked', false);
$response.show(300).delay(2500).hide(400);
}
if (response.info === 'server_fail') {
$response.find('p').append('Server failed. Send later!');
$response.show(300);
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $response.offset().top - 50;
if ($(document).scrollTop() < bottomPosition) {
$('html, body').animate({ scrollTop : bottomPosition });
}
});
return false;
});
});
}
sorry, html, php and js are together, didn't manage to make something better...
thanks a lot guys !!!
remi
remove these lines :
$verify = $_SESSION['verify'];
if ($verify != md5($data['verify'])) {
$errors["verify"] = "Please enter correctly captcha";
}
I have this landing page with contact form which is working without any problems on my regular hosting but It doesn't want to work on this VPS I was given access to. When I click "Send" button nothing is happening and email is not being sent. I checked mail() function and it seems to work on their server.
What could be the reason for ajax/json not working on this server?
Here's the JS code (core.js):
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Email sent. Thank you.</p>');
}
});
return false;
});
};
The PHP file (send-email.php):
<? if($_SERVER['REQUEST_METHOD'] == "POST" ) {
$destination = 'myemail#example.com'; // change this to your email.
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
And HTML:
<form class="contact" id="contact">
<div class="form">
<input type="text" name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Send</button>
</div>
</form>
The statement var emailValidation = false; inside IF is makes the variable emailValidation local to it. Similarly other variables too are local. Declare them in global scope, outside the conditions.
try using
$("#contact").serializeArray()