Contact form don't send well - php

I have a problem when sending data to the contact form. Data is sent to e-mail only if you click many times, but if you tab to move to the button and press enter data is sent immediately. But still fall into the spam.
HTML
<div id="f1" class="contact_wrapper">
<form>
<div id="r2"></div>
<input type="text" name='rname' id="names" class="name" placeholder="Ваше имя">
<input type="email" name='email' id="eml" class="email" placeholder="Ваше Email">
<input type="text" name='subject' id="phon" class="contact_number" placeholder="Контактный телефон">
<textarea name="message" id="masage" cols="30" rows="10"></textarea>
<input name="" id="button" type="button" value="Отправить" class="submit" onclick="mail2('Радиус-01 Оформить заявку - последняя форма','names','eml','phon','masage','f1','r2')">
</form>
</div>
AJAX
<script>
function mail2(subject,names,eml,phon,masage,f,rr){
var names = document.getElementById(names).value;
var eml = document.getElementById(eml).value;
var phon = document.getElementById(phon).value;
var masage = document.getElementById(masage).value;
var frt = document.getElementById('generator_konr').value;
var params = {subject:subject,names:names,eml:eml, phon:phon,masage:masage,kon:frt};
$.ajax({
type: "POST",
url: "mail2.php",
data: params,
success: function(data){
$('#ertretgfdg').html(data).fadeIn("slow");
}
});
}
</script>
mail2.php
<?
### Referals script start
$debug=0;
function writelog($s) {
global $lf,$debug;
if ($debug)
fputs($lf,"$s\n");
}
if ($debug)
$lf=#fopen(dirname(__FILE__).'/'.'debug.log','a');
$t=date('Y-m-d H:i:s');
$utm='нет';
$term='нет';
$ip=$_SERVER['REMOTE_ADDR'];
$utmdata='';
writelog("Session started (zakaz.php) at '$t', IP='$ip'");
writelog("REQUEST: ".print_r($_REQUEST,true));
if (isset($_COOKIE['utmdata'])) {
writelog("Found saved cookie UTMdata");
$utmdataexp=explode('&',$_COOKIE['utmdata']);
if (count($utmdataexp)>=2 && !empty($utmdataexp[0]) && !empty($utmdataexp[1])) {
$t=$utmdataexp[0];
$utm=$utmdataexp[1];
$term=isset($utmdataexp[2]) ? $utmdataexp[2] : 'нет';
$utmdata=$t.'&'.$utm.'&'.$term;
}
}
writelog("UTMdata is '$utmdata'");
### Referals script end
$phon = $_POST['phon'];
$names = $_POST['names'];
$subject = $_POST['subject'];
$kon = $_POST['kon'];
$eml = $_POST['eml'];
$masage = $_POST['masage'];
if ($names=='' or $names=='Введите ваше имя') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите свое имя");</script>';
exit;
}
if ($phon=='' or $phon=='Ваш телефон' or $phon=='Введите номер телефона') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите номер телефона");</script>';
exit;
}
if ($eml=='' or $eml=='Ваш email' or $eml=='Введите ваш email') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваш email");</script>';
exit;
}
if ($masage=='' or $masage=='Ваше сообщение' or $masage=='Введите ваше сообщение') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваше сообщение");</script>';
exit;
}
$er=null;
if ($subject=='Выбран конкретный генератор') {
$ert='Генератор: '.$kon.'<br/>';
}
$body ='
По вопросу: '.$subject.'<br/>
'.$ert.'
Имя: '.$names.'<br/>
Телефон: '.$phon.'<br/>
Мыло: '.$eml.'<br/>
Сообщение: '.$masage.'<br/>
Рекламная площадка:</b> '.$utm.'<br />
Ключевое слово: '.$term.'<br />
';
$email='myemail#gmail.com';
$headers = "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: <".$em.">\r\n";
if (mail($email, $subject_t, $body, $headers)) {
echo '<script>$().toastmessage(\'showSuccessToast\', "Сообщение успешно отправлено");</script>
<script>$(".header .sform").delay( 2000 ).slideToggle();</script>';
exit;
} else {
echo '<script>$().toastmessage(\'showErrorToast\', "Ошибка, повторите попытку");</script>';
exit;
}
?>
<!--

Related

Sending an email with ajax and object oriented php best practices

I am building a form to send an email and I want to use Object Oriented Php and Ajax.
I was able to build the PHP backend (variable and function) regardless of Ajax, but I have problems in making the Ajax call because I have not yet understood what are the steps to follow.
My problem is that I don't really understand how the ajax URL works (the call the to PHP file). Should I try to target the function (and how can I do) or should I call the page directly, in which I'm gonna create the json function to output a json file to parse with ajax?
Here's my code:
Footer.php and main.js
$('#contact-form').on('submit',function(e) {
e.preventDefault();
$('.output-message').text('Loading...');
const form = $(this);
const post_url = $(this).attr("action");
console.log(post_url);
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
if (result == 'success'){
$('.output-message').text('Message Sent!');
} else {
$('.output-message').text('Error Sending email!');
}
}
});
return false;
});
<form id="contact-form" name="contact-form" action="Contact.php" method="POST" data-parsley-validate="">
<div class="row">
<div class="col-md-6">
<div class="md-form mb-0">
<input type="text" id="name" name="name" class="form-control" required="">
<label for="name" class="">Your name</label>
</div>
</div>
<div class="col-md-6">
<div class="md-form mb-0">
<input type="email" id="email" name="email" class="form-control" required="">
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea" required=""></textarea>
<label for="message">Your message</label>
</div>
</div>
</div>
<div class="text-center text-md-right">
<input type="submit" id="submit" class="btn-primary" name="submit" value="Request Info">
<span class="output-message"></span>
</div>
</form>
And the php Class:
Contact.php
<?php
class Contact {
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
echo '<p class=\'message error\'>';
echo '<font color="black">' . $errors . '</font>';
echo '</p><br />';
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
$sendMail->sendMail();
}
?>
The javascript part doesn't work, and I'm trying to understand this part:
const post_url = $(this).attr("action");
$.ajax({
url: post_url,
Should I create another function in PHP that will output a JSON file that collects all the variables?
My though is that I'm serializing the URL and then I will send it to the PHP file, but I'm not even able to console.log() the result.
Refactor a little bit :
class Contact
{
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
throw new Exception($errors, 400);
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
header('Content-Type: aaplication/json');
try {
$sendMail->sendMail();
echo json_encode(array('success' => 'success'));
} catch (Exception $e) {
header ('HTTP/1.1 400 Bad Request')
$errors = array('error' => $e->getMessage);
echo json_encode($errors);
}
}
I've made it return the string instead of echoing in the class, and I've thrown an exception on an error. Also, since we are sending to JS I made it return JSON.
Lastly, change the JS here:
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
$('.output-message').text('Message Sent!');
}
error: function(result) {
console.log(result);
$('.output-message').text('Error Sending email!');
}
});
JS will check a 200, so know if it is success. Since you now send a 400 on error, the error function will trigger! Give that a try :-)

How can i add recaptcha properly to my html form?

I have an AJAX HTML form with validation fields. So my problem is that i'm stuck. I want to embed a recaptcha in my form. I want to produce the following result. If the user completes the recaptcha then the form will be sended. Now if i complete the form and the recaptcha correctly the form is not sended.
HTML
function sendContact() {
var valid;
valid = validateContact();
if(valid) {
jQuery.ajax({
url: "contact_mail.php",
data:'userName='+$("#userName").val()+'&userEmail='+$("#userEmail").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
}
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color','');
$(".info").html('');
if(!$("#userName").val()) {
$("#userName-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userName").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#userEmail").val()) {
$("#userEmail-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userEmail").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#userEmail").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#userEmail-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#userEmail").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#subject").val()) {
$("#subject-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#subject").css('background-color','#3E3E3E');
valid = false;
}
if(!$("#content").val()) {
$("#content-info").html("<span style='color: #F00423';>Απαιτούμενο πεδίο</span>");
$("#content").css('background-color','#3E3E3E');
valid = false;
}
return valid;
}
</script>
<div id="frmContact">
<div id="mail-status"></div>
<div>
<span id="userName-info" class="info"></span><br/>
<input type="text" name="userName" id="userName" class="form-control form-dark demoInputBox" placeholder="Όνομα">
</div>
<div>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="form-control form-dark demoInputBox" placeholder="Email">
</div>
<div>
<span id="subject-info" class="info"></span><br/>
<input type="number" name="subject" id="subject" class="form-control form-dark demoInputBox" placeholder="Τηλέφωνο">
</div>
<div>
<span id="content-info" class="info"></span><br/>
<textarea name="content" id="content" class="form-control form-dark demoInputBox" cols="60" rows="6" placeholder="Μήνυμα"></textarea>
</div>
<div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6LcoXZ0UAAAAAMdgKIlchJvizDWic5S7nwr5XD3g"></div>
<button name="submit" class="btn btn-border border-white btnAction" onClick="sendContact();">Αποστολη</button>
</div>
</div>
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// access
$secretKey = '6LcoXZ0UAAAAAF3U4SSfiKPZ7NWyuATN7NFh8fKE';
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
exit;
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
} else {
$to = "vp#digital-media.gr";
$msg = "name:\t$_REQUEST[userName]\n";
$msg .= "email:\t$_REQUEST[userEmail]\n";
$msg .= "tel:\t$_REQUEST[subject]\n";
$msg .= "message:\t$_REQUEST[content]\n";
$success = mail($to, "Mail from our site", $msg, "Content-type: text/plain; charset=UTF-8");
if($success) {
print "<p class='success'>Ευχαριστούμε, το μήνυμα σας έχει σταλθεί. Θα σας απαντήσουμε το συντομότερο.</p>";
} else {
print "<p class='Error'>Υπήρξε ένα σφάλμα, δοκιμάστε αργότερα! </p>";
}
}
?>

PHP form with response on same page

Hi I created a PHP form - I am getting the email but the the response message opens in the same window with plain text. If someone could point me in the right direction that would be great.
This is the output once submitted:
{"status":"success","message":"Thank you for your interest in Nature's Apprentice.
A representative will be in contact with you shortly","email_sent":true}
This is the contact form code:
<form name="formContact" id="formContact" action="contact-submit.php" method="post" novalidate="novalidate">
<label for="name">Name <span class="required" >*</span></label>
<input name="name" id="name" class="form-control " placeholder="First and Last Name" type="text">
<label for="email">Email <span class="required" >*</span></label>
<input name="email" id="email" class="form-control" placeholder="email#domain.com" type="text">
<label for="phone">Phone</label>
<input name="phone" id="phone" class="form-control" placeholder="(xxx) xxx-xxxx" type="text">
<label for="address">Area of Interest </label>
<input name="address" id="address" class="form-control" placeholder="Location" type="text">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" placeholder=""></textarea>
<input name="submit" id="submit" class="submit_btn" value="Submit" type="submit">
<img src="images/loader.gif" alt="Loader" class="loader">
<div class="info_msg">
<p><span class="required">*</span> indicates required field.</p>
</div>
<div class="response_msg">
<p></p>
</div>
</form>
This is the js:
jQuery(document).ready(function ($) {
$("#formContact").validate({
ignore: ".ignore",
rules: {
name: "required",
email: {
required: true,
email: true
}
},
invalidHandler: function (form, validator) {
$('#formContact').find('#response_msg p').removeClass().addClass('error').html('Please fill all the required fields.');
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(), // serializes the form's elements.
beforeSend: function(){
$('img.loader').fadeIn();
},
success: function (data) {
var json = $.parseJSON(data);
//alert(json.status , json.message);
$('#formContact').find('#response_msg p').removeClass().html('');
if(json.status !='') {
if(json.status == 'success') {
$('#formContact').trigger('reset');
}
setTimeout(function(){
$('#formContact').find('#response_msg p').removeClass().addClass(json.status).html(json.message).fadeIn();
}, 1000);
}
},
error:function (xhr, ajaxOptions, thrownError){
$('#formContact').find('#response_msg p').removeClass().addClass('error').html('Some error occured. Please try again.').fadeIn();
},
complete: function(){
$('img.loader').fadeOut();
}
});
}
});
});
</script>
This is the contact-submit.php:
//session_start();
require 'include/include.php';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$address = trim($_POST['address']);
$comments = trim($_POST['comments']);
$errors = array();
if($name == '' or $email == '' ) {
$response = array('status' => 'error', 'message' => 'Please fill all the required fields.');
echo json_encode($response);
exit;
}
else {
if(strlen($name) < 3) {
$errors[] = 'Name should be 3 characters long.';
}
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter valid email.';
}
$errors = array_filter($errors);
if (!empty($errors)) {
$message = implode("<br>", $errors);
$response = array('status' => 'error', 'message' => $message );
echo json_encode($response);
exit;
}
else {
$mailsubject = "Contact Us Form Details - ".$site_name;
$sendmessage = "Dear Administrator,<br /><br />
<b>Name:</b> $name<br /><br />
<b>Email:</b> $email<br /><br />
<b>Phone:</b> $phone <br /><br />
<b>Address:</b> $address <br /><br />
<b>Comments:</b> $comments <br /><br />";
$mail_str = "";
$mail_str = '<html><head><link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"></head><body style="max-width: 600px; margin: 0 auto; font-family: Open Sans, sans-serif; font-size: 15px; line-height: 20px;"> <table style="border:1px solid #000000" width="95%" align="center" cellspacing="0" cellpadding="0"> <tbody><tr style="background-color:#365744"><td style="padding: 10px; ">'.$site_name.'</td></tr><tr style="background-color:#ffffff"><td style="padding: 10px; ">'.$sendmessage.' </td></tr><tr style="background-color:#383634; color: #fff;"><td style="padding: 10px; ">Thanks! - '.$site_name.'</td></tr></tbody></table></body></html>';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = sprintf('From: %s <%s>', $name, $email);
$headers = implode("\r\n", $headers);
#echo "<hr/>"; echo $to_mail;echo "<hr/>";echo $mailsubject;echo $mail_str; echo $headers; exit;
$emailsend = mail($admin_email, $mailsubject, $mail_str, $headers);
if($emailsend) {
$response = array('status' => 'success', 'message' => sprintf('Thank you for your interest in %s. <br /> A representative will be in contact with you shortly', $site_name), 'email_sent' => $emailsend);
echo json_encode($response);
exit;
}
else {
$response = array('status' => 'error', 'message' => 'Some error occured. Please try again.', 'email_sent' => $emailsend);
echo json_encode($response);
exit;
}
}
}
#---------------Mail For Admin (Ends)--------------------------------------------------
//header("Location:thank-you.html");
exit;
?>```
According to your code class="response_msg" should be id="response_msg" in your form.
You should be setting the header when returning json.
header('Content-Type: application/json');
Try adding a preventDefault call. Otherwise, the form is probably being submitted via the normal form POST process after your Ajax is finished and thus is redirecting to the contact-submit.php page and you see the echo out of the response on a blank page.
Try this edit:
...
submitHandler: function (form, e) {
e.preventDefault();
$.ajax({
type: "POST"
...
I've debugged your code and tested it as working. You need to add the following 4 changes:
Specify the data type to jQuery. Add the dataType line as below.
data: $(form).serialize(), // serializes the form's elements.
dataType: 'json',
beforeSend: function(){
Let jQuery do the JSON parsing. Change this:
success: function (data) {
To this:
success: function (json) {
Get rid of this line:
var json = $.parseJSON(data);
Your #response_msg selector is off, because you've given the container a .response_msg class, instead of an id. Change this:
<div id="response_msg">
To this:
<div class="response_msg">
Or change the selectors to refer to the class instead.
And things should then work as expected.

How to validate captcha field code?

I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>

display alert when form is submitted

I need to display the alert saying thanx your msg is received but this doesnot works so please hel me out how to do.Is there coding error or what i coudnt get to it.i would pe pleased if someone helps me out.thankyou
<h4>Send Your Feedback Here.<p>
<form name ="register" action="contact.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="validate()">Send</button>
</p>
</form>
<script type="text/javascript">
function validate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y)
{
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="")
{
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="")
{
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="")
{
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="")
{
alert(msg);
}
else
{
<?php
//Get message data.
$name = $_POST['name'];
$message = $_POST['message'];
$email=$_POST['email'];
$ver = $_POST['ver'];
$rval = $_POST['rval'];
if($ver==$rval)
{
//Email it.
mail(
'example#example.com', //Where to send
"Contact form - $name", //Email subject
$message, //Message body
$email //email address
);
echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>";
}
else
{
echo "<script type=\"text/javascript\">alert('Wrong captcha');</script>";
}
?>
}
}
You can't mix JavaScript and PHP like that. The PHP will be parsed on the served before the page is served up to the user. Including it inside of your JavaScript else block will have no effect, since the code will be run when the page is generated anyway.
You should look into the use of AJAX.
<script type="text/javascript">
function thevalidate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y) {
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="") {
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="") {
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="") {
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="") {
alert(msg);
} else {
<?php
//You need to process data here..
?>
}
}
</script>
<h4>Send Your Feedback Here.<p>
<form name ="register" action="php/process.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="thevalidate()">Send</button>
</p>
</form>

Categories