Cleaning my php contact form from captcha - javascript

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";
}

Related

Getting a form to send an selected option to email

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'];
}
}

ajax jquery form stopped sending emails

I have a form which was sending emails from the server before but all of a sudden it stopped working. I cant seem to figure out the issue. When I use the form without ajax then email works perfectly. I saw http 200 code in the dev tools and no errors. Any help would be much appreciated. Thank you.
html:
<form id="form1" class="form-action" action="" method="POST">
<input type="text" name="name" id="name" class = "name" required />
<input type="email" name="email" id="email" required />
<input type="text" name='company' id="company" class="company" required />
<textarea class= "message" name="message" id="message" required />
</textarea>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div class="g-recaptcha" data-sitekey="x" data-callback="recaptcha"></div>
<button type="submit" id="submit-button">Submit</button>
<span class="success_message font-weight-bolder text-center hide" style="margin-left: 30px;">
message received.</span>
</form>
<script>
function reset_form(){
$("#form1")[0].reset();
}
function reset_success_message(){
$('.success_message').addClass('hide');
}
$(document).ready(function(){
$('#name').click(function () {
$('.success_message').addClass('hide');
});
$('.email').click(function () {
$('.success_message').addClass('hide');
});
$('.company').click(function () {
$('.success_message').addClass('hide');
});
$('#message').click(function () {
$('.success_message').addClass('hide');
});
$('#form1').submit(function (e) {
$('.success_message').addClass('hide');
e.preventDefault();
$.ajax({
url: 'serverside.php',
type: 'post',
data: $('#form1').serialize(),
success: function (response) {
if(response == 'submitted'){
reset_form();
$('.success_message').removeClass('hide');
}
}
});
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
serverside.php
<?php
$email_to = 'x#domain.com';
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true) {
mail($email_to, $email_subject, $email_content, "From:" . $email);
}
else
{
}
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
You seem to be missing the Recaptcha secrets. Removing the Recaptcha if condition it works fine.
<?php
$email_to = 'ahmed_rises#hotmail.com'; //-----------> Invalid Email Id was added here
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
//Recaptca Secrets are Missing?????? Random string passed!
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret="
.$recaptcha_secret."&response=".$_POST['g-recaptcha-response']); //-----> Also Recapta response from
//the form is also missing since there its not working and neither getting passed
$response = json_decode($response, true);
//Printed the Output in which it shows the recapta Error
echo "<pre>";
print_r($response);
//If you ae to remove the Recapta Condition, the mail will be send!
// if($response["success"] === true) {
echo "==========";
echo "email_subject:".$email_subject.", email:".$email.",email_to:".$email_to;
mail($email_to, $email_subject, $email_content, "From:" . $email);
echo "==========";
// }
// else
// {
// echo "Failed";
// }
echo "<br>";
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
Hope it helps :)

php is not getting any request from ajax type post and is it require to mention username and password in mail

I'm working on contact page form to send emails.
I have written HTML form to get user details and performing form validations in contactform.js file. In the same JavaScript file I have written ajax POST call to call contact_mail.php.
I have found many similar questions over the internet but the problem is - in my local machine on form Submit button php is getting called, but this is not happening in remote web server.
If I avoid call to contactform.js by removing class="contactForm" from my form definition, php is getting called but I loose all the validation. :( If i call contactform.js by specifying class="contactForm" in form definition then validation are performed nicely but nothing happens on submit since no call to PHP.
I don't know what am I doing wrong...
Here is my code...
HTML form looks like this:
<form action="contactform/contact_mail.php" method="post" role="form" class="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="phone" class="form-control" name="phone" id="phone" placeholder="Your Contact" data-rule="phone" data-msg="Please enter a valid contact number" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
</div>
This is my javascript contactform.js file
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function(e) {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i,
phoneExp = ^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$;
/*phoneExp = /^\d{10}$/;*/
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'phone':
if (!phoneExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'contactform/contact_mail.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
// alert(msg);
if (msg == 'OK') {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
My contact_mail.php file
<?php
/* send mail new*/
/* start - send mail */
require_once('contactform/class.phpmailer.php');
require_once('contactform/PHPMailerAutoload.php');
require_once('contactform/class.smtp.php');
if(isset($_POST["Submit"]))
{
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$body = '<html><body>';
$body .= '<h2>Customer Enquiry </h2><br>';
$body .= '<table rules="all" style="background-color: #EBF4FA;" cellpadding="10">';
$body .= "<tr><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['name']) . "</td></tr>";
$body .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['email']) . "</td></tr>";
$body .= "<tr><td><strong>Contact No. :</strong> </td><td>" . strip_tags($_POST['phone']) . "</td></tr>";
$body .= "<tr><td><strong>Message:</strong> </td><td>" . strip_tags($_POST['message']) . "</td></tr>";
$body .= "</table>";
$body .= "</body></html>";
$to = "receiver address";
$subject = " Enquiry Form";
$headers = "From: info#xyz.com" . "\r\n" .
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$res="OK";
if (mail($to,$subject,$body,$headers))
{
return $res;
}
else
{
return false;
}
header( "refresh:0;url=index.html");
}?>
Actually, I am learning php language at beginner level.
What should do to send mail successfully and get success or failure message.
It appears the submit form handler is not preventing the default submitted event. Try adding '''e.preventDefault()''' at the start of the handler.

send form data to admin email in codeIgniter

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

check php variable in javascript function

I've downloaded a template for web.
In this template, there is a php script to send email. In this script there is a validate() function, in which there is a variable $return_array. one of its value is $return_array['success'] that could be '0' or '1'. In another file, a javascript one, there is a click() function, that manages the value of 'success' in the php script doing if(html.success == '1')...but it does not work as expected, infact it is always '0'...what do I need to check?
Here is the html form:
<form method="POST" action="send_form_email.php" id="contactform">
<div>
<label for="name" style="color:white;">Inserisci il tuo nome</label>
<input type="text" class="input-field" id="name" name="name" value="">
</div>
<div>
<label for="email" style="color:white;">Inserisci la tua e-mail</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<div>
<label style="color:white;">Scrivi il tuo messaggio</label>
<textarea id="message" name="message" style="min-height: 160px;"></textarea>
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Invia E-Mail</a>
<div id="success">Il tuo messaggio &egrave stato inviato correttamente!</div>
<div id="error">Impossibile inviare il messaggio. Riprovare pi&ugrave tardi.</div>
</form>
and here is the function into the php
<?php
// EDIT THE 2 LINES BELOW AS REQUIRED
$send_email_to = "mail.address#email.com";
$email_subject = "Feedback subject";
function send_email($name,$email,$email_message)
{
global $send_email_to;
global $email_subject;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$return_array = validate($name,$email,$message);
if($return_array['success'] == '1')
{
send_email($name,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
and following the javascript code:
$('#button-send').click(function(event){
$('#button-send').html('Invio in corso...');
event.preventDefault();
//$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contactform').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Invia E-Mail');
$('#success').show();
}
else
{
$('#button-send').html('Invia E-Mail');
$('#error').show();
console.log(html);
}
},
error: function(){
$('#button-send').html('Invia E-Mail');
$('#error').show();
console.log("not html.success");
}
});
});
EDIT:
I've edited the php part adding at the end the json_encode and content type, but when there is an error, like name missing or mail missing, I expect to see something appears near the input form, but it does not...
Use return json_encode($return_array); Instead of return $return_array;.
Json encode returns key => value pair array .
Also use dataType: "json" OR dataType: "jsonp" in ajax call.

Categories