Contact form sending blank emails sometimes, although working perfectly - javascript

there is a form I created, but many times emails show up with nothing in the body. The input fields are coming blank. I’ve tried finding the cause, but I haven’t been able to rectify the problem. Does anyone know what might be causing this? and how to resolve this.
I am using this contact form for downloading pdf.
Here is the code:
<div class="modal fade" id="over">
<p id="messageDownload" style="display:none;">Thank you for download, we will contact you shortly!</p>
<div class="modal-dialog">
<div class="modal-content">
<div class="panel panel-default contact bg-edit bg-blue" style="margin-bottom:0;max-width:500px;">
<div class="panel-body">
<form id="loginForm" novalidate="novalidate">
<div class="row" style="max-width:500px;">
<p class="text-uppercase my-font-style" align="center">Fill Your Contact Details</p>
<div class="col-md-12">
<input id="name1" type="text" class="form-control" placeholder="Name" name="name1" required>
</div>
<div class="col-md-12">
<input id="email1" type="email" class="form-control" name="email1" placeholder="Email" required>
</div>
<div class="col-md-12" style="margin-bottom: 15px;">
<input id="mobile1" placeholder="Phone" name="mobile1" type="text" class="form-control input-inverse iti-phone" required>
</div>
<div class="col-md-12 text-center">
<input type="hidden" name="site_name" value="<?php echo $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; ?>" />
<button onclick="insert()" type="button" class="btn btn-white" name="sub">Download</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!--End Download Modal-->
<!--start donwload link-->
<div>
<a id="link" href="abc.pdf" class="" download hidden></a>
<button type="button" data-bname="abc.pdf" onclick="document.getElementById('link').href=this.getAttribute('data-bname'); Dat()" class="theme-btn btn-style-one"> Download</button>
</div>
<!--End Download link-->
<!-- start download.js -->
<style>
function insert() {
var name1 = $("#name1").val();
var namev = /^[a-zA-Z ]*$/;
var email1 = $("#email1").val();
var emailv = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var mobile1 = $("#mobile1").val();
var mobilev = (/^[0-9]+$/);
if (name1 === null || name1 === "" || namev.test(name1) === false) {
alert("Please enter your name.");
return false;
} else if (email1 === null || email1 === "" || emailv.test(email1) === false) {
alert("Please enter email.");
return false;
} else if (mobile1 === null || mobile1 === "" || mobilev.test(mobile1) === false) {
alert("Please enter your mobile.");
return false;
} else {
var formdata = $("#loginForm").serialize() + '&c_code1=' + document.getElementsByClassName('selected-flag')[0].title;
$.ajax({
type: "POST",
url: "download_send.php",
data: formdata,
success: function(data) {
$("#messageDownload").css('display', 'block');
$('#loginForm').html($("#messageDownload"));
$("#messageDownload.p").addClass("alert-default");
},
});
}
document.getElementById('link').click()
setTimeout(function() {
$('#over').modal('hide');
}, 10000);
}
</style>
<!-- end download.js -->
<!-- start download_send.php -->
<?php
date_default_timezone_set("Asia/Dubai");
$ddate = date(' d-m-Y H:i:s');
function get_client_ipsp() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if (isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
extract($_POST);
$site_name = str_replace("http://", "", $site_name);
$site_name = str_replace(".php", "", $site_name);
$msg = "Name:- " . $name1 . "\r\n" . "Email:- " . $email1 . "\r\n" . "Phone:- (" . $c_code1 . ")" . $mobile1 . "\r\n" . "IP Addr:- " . get_client_ipsp();
$headers = "From: $name1 <enquiry#abc.com>" . "\r\n" . "CC: enquiry#abc.com" . "\r\n" . "BCC: leads#abc.com";
mail("sales#abc.com", $ddate . ' Enquiry from ' . $site_name . '(Download Form)', $msg, $headers);
echo'your message has been sent';
?>
<!-- end download_send.php --> ```

Related

How can I rewrite the HTML page to have the exact same fields?

I'm trying to make a new look for my website, but it looks like it doesn't want to login and I don't understand why.. Here's the original page:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
And here's the edited page:
<!-- To keep it in the center of page-->
<img class="wave" src="img/wave.png">
<div class="container_main">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form>
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
What am I doing wrong? I don't want to use the body class jumbotron vertical-center cause it's making my website to look very awful.. I always get ,,XHR loading failed" and I don't understand why..
My checklogin.js file:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
}
});
}
And my login.php file:
<?php
include "mysql-connect.php";
//get Info from login.html
$ID = $_GET['enterID'];
$PW = $_GET['password'];
$stmt = $connect->prepare("SELECT PW, userType, nickName FROM users WHERE ID = ?");
$stmt->bind_param("s",$ID);
$valid = $stmt->execute();
if (!$valid){
die("Could not successfully run query.". $connect->connect_error);
}
$result = $stmt->get_result();
if ($result->num_rows==0){
//display message of no such student/teacher/admin
echo "Failed to find an account with the input ID.";
} else {
$row = $result->fetch_assoc();
if (password_verify($PW, $row['PW'])) {
$type = $row['userType'];
$nick = $row['nickName'];
//var_dump($row['PW']);
//save data
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["type"]=$type;
$_SESSION["userID"]=$ID;
$_SESSION["nickName"]=$nick;
//login success - Request.responseText to checklogin.js
echo $type;
} else {
//display message of password error
echo "The input password does not match the account password.";
}
}
$connect->close();
?>
And here's the redirect.php:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>

email file attachment php, Ajax, Jquery

i have problem with email file attachment php, Ajax, Jquery on the following codes, also i need the file attachment field mandatory. the uploaded file in the form doesn't pass to the email!
i need to place code into the Ajax to receive file(s) from the form and check the empty field, then it everything goes fine pass the fields include file(s) to the form. and from the form to the Email.
HTML Form:
<form role="form">
<div class="form-group">
<label for="inputName" class="form-label "></label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail" class="form-label "></label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage" class="form-label "></label>
<input type="text" class="form-control" id="inputMessage" placeholder="Phone Example:+1234567890"></textarea>
</div>
</form>
<button type="button" class="btn sign-btn-primary submitBtn" onclick="submitContactForm()">Request</button>
<p class="statusMsg"></p>
my php file :
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'info#test.org';
$subject= 'CCI2017 Download Log';
$htmlContent = '
<h4>The CCI 2017 has been downloaded by person, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Phone:</th><td>'.$message.'</td>
</tr>
</table>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: ME' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
my jquery:
<script type="application/javascript">
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (message.trim() != '' && !regp.test(message)) {
alert('Please enter your Phone.');
$('#inputMessage').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_form.php',
data: 'contactFrmSubmit=1&name=' + name + '&email=' + email + '&message=' + message,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
if (msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('Download');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Solutions:
<form role="form">
<div class="form-group">
<label for="inputName" class="form-label "></label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail" class="form-label "></label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage" class="form-label "></label>
<input type="text" class="form-control" id="inputMessage" placeholder="Phone Example:+1234567890"></textarea>
</div>
</form>
<button type="button" class="btn sign-btn-primary submitBtn" onclick="submitContactForm()">Request</button>
<p class="statusMsg"></p>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="application/javascript">
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (message.trim() != '' && !regp.test(message)) {
alert('Please enter your Phone.');
$('#inputMessage').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_form.php',
data: 'contactFrmSubmit=1&name=' + name + '&email=' + email + '&message=' + message,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
if (msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('Download');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Submit_form.php
<?php
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$to = 'kiran.mind2014#gmail.com';
// Subject
$subject = 'CCI2017 Download Log';
// Message
$message = '
<h4>The CCI 2017 has been downloaded by person, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Phone:</th><td>'.$message.'</td>
</tr>
</table>
';
// 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[] = 'To: Kiran <kiran.mind2014#gmail.com>';
$headers[] = 'From: CCI2017 Download Log <kiran.mind2014#gmail.com>';
// Send email
if(mail($to, $subject, $message, implode("\r\n", $headers))){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
It is working fine!!!.

How to send the drop down list value to an email? [duplicate]

This question already has an answer here:
How to send the selected value of a drop down menu to an email?
(1 answer)
Closed 4 years ago.
I have an question that I need to send selected drop down list value to an email.I already sent the other input values in the contact form to an email. But I do not know how to send the drop down list value to an email. Herewith attached the html, php and js code. Could anyone can help me?
Here is the html code
<!-- Contact form -->
<div class="modal fade" id="modalForm" role="dialog" style="width: 100%;">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name" style="border: 1px solid #fff; border-bottom: 1px solid #ccc;"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<label for="inputService">Service</label>
<select name="subject" class="form-control"
id="inputService" size="1">
<option value="Option1">Pr-Matrimonial Services</option>
<option value="Option2">Extra Marital Affairs</option>
<option value="Option3">Divorce Case Support</option>
</select>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JS code...
<script>
function submitContactForm(){
var usernameRegex = /^[a-zA-Z0-9]+$/;
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(name.trim() != '' && !usernameRegex.test(name)){
alert('Please enter valid name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'contact.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
php code...
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$option= $_POST["subject"];
/*
* Send email to admin
*/
$to = 'support#ribelz.net';
$subject= 'Contact Request of privateeyelk.com';
$htmlContent = '
<h4>Contact request from : '.$email.'</h4>
<p>Name: '.$name.'</p>
<p>Email: '.$email.'</p>
<p>Message: '.$message.'</p>
<p>Service: '. $option.'</p>
';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: Private Eye<privateeyelk.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
You didn't retrieve the value of select in your Js code
Try adding this line in your submitContactForm function
var subject = $('#inputService').val();
Please check this line to
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message+'&service='+subject,

open bootstrap modal from script in another page in php

in my application there is an inquiry form. My task is when i submit the inquiry form it send an email and if email is sent successfully I have to show a success message in a modal. I am writing my sendemail code inside index.class.php file. I have to show the modal in services.php file. How can I do that. I tried it by header location but it doesn't work. I didnt know whether it was right or not.
Here is my code:
index.class.php
case "submitservceEnquiryMedical":
$mcpage = "services.php";
if($this->sendMedicalservceenquiryEmail()) {
$flmsg="success";
}
else {
$flmsg="fail";
}
header("Location: services.php?flMsg=$flmsg");
exit();
break;
Services.php
if(!EMPTY($_REQUEST['flmsg']))
{
$flmsg=$_GET['flmsg'];
if($flmsg=='success')
{
echo '<script> $("#Service-Enquiry").modal("show"); </script>';
}
else{
echo '<script> $("#Service-Enquiry").modal("show"); </script>';
}
}
<div class="modal fade" id="modal-success">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Success</h4>
</div>
<div class="modal-body">
<p>You have succesfully submitted</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Can anyone please help me
In my opinion here there are differents problems you can't use header location in that way and you are doing javascript injection inside php that really in this case no need.
My solution, or better what i do in my site it's this:
I do an ajax call to the PHP method(page, function, method it's the same), that sends the email, passing all the value from ajax and print an answer to the client/ajax in case the mail was sent or not...so OK or KO(in my case 00 is OK) and in the success of the ajax call i manage the answer 00 so ok etc....In your way you must do an ajax call to this
sendMedicalservceenquiryEmail()
Return the flag and after in ajax at the success, if flag is success then modal show...I try to attach you my code if can be of help, just to look the architecture.
Code PHP where i do the ajax call, passing name, message, object of the email and destinatario is the recipient:
setlocale(LC_TIME, 'it_IT');//Settiamo il timezone per l'orario
date_default_timezone_set("Europe/Rome");
$data = date("d-m-Y");
$ora = date('G:i:A');
/**
* SESSION
*/
$datiUtente = $_SESSION['datiUtente'];
$utente = $datiUtente['username'];
$profilo = $datiUtente['profilo'];
$email = $_REQUEST['destinatario'];
$nome = $_REQUEST['nome'];
$to = $email;
$messaggio = trim($_REQUEST['messaggio']);
$oggetto = trim($_REQUEST['oggetto']);
$mittente = 'YOUR ACCOUNT#MAIL';
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$msg = '88'.'|';
$error='background: url("../img/error.png") no-repeat scroll left top #ffd0dc;
border: 1px solid #ac343d;
margin: 5px 0 15px;
padding: 5px 5px 5px 40px;';
$msg .= ("<div style='$error'>Formato Email non valido</div>");
$msg = str_replace('\n', '', $msg);
$msg = str_replace('\r', '', $msg);
print $msg;
exit;
}
$message = "Email in arrivo da server <b>$mittente</b><br/>
Inviata da : <b>$nome </b><br/>
Profilo utenza : <b>$profilo </b><br/><br/><br/>
$messaggio ";
$subject = $oggetto;
$menof = "'-f" . trim($mittente) . "'";
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
$eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
$eol="\r";
} else {
$eol="\n";
}
$now = rand();
$headers = 'From: YOUR NOME YOURSURNAME<YOUR ACCOUNT MAIL>'.$eol;
$headers .= 'Reply-To: YOUR NOME YOURSURNAME<YOUR ACCOUNT MAIL>'.$eol;
$headers .= 'Return-Path: YOUR NOME YOURSURNAME<YOUR ACCOUNT MAIL>'.$eol; //risposta a...
$headers .= "Message-ID:<".$now." TheSystem#".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; //Per non andare nello spam
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: text/html; boundary=\"".$mime_boundary."\"".$eol;
if (mail(trim($to), trim($subject), wordwrap(trim($message)), trim($headers),trim($menof))){
$msg = '00'.'|';
$msg .= ("L'email è stata inviata correttamente");
$msg = str_replace('\n', '', $msg);
$msg = str_replace('\r', '', $msg);
print $msg;
exit;
}
else{
$msg = '99'.'|';
$msg .= ("Invio Email FALLITO!!!");
$msg = str_replace('\n', '', $msg);
$msg = str_replace('\r', '', $msg);
print $msg;
exit;
}
At the click of the button send mail i invoke this function that does the call at the php over
function inviaEmailCliente(){
var nome = $('#nomeMail').val();
var messaggio = $('#messaggioMail').val();
var oggetto = $('#oggettoMail').val();
var destinatario = $('#destinatarioMail').val();
if (oggetto == false){
$('#contenutoInserimentoAna').html('Oggetto Obbligatorio');
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
return;
}
if (messaggio == false){
$('#contenutoInserimentoAna').html('Messaggio Obbligatorio');
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
return;
}
if (nome == false){
$('#contenutoInserimentoAna').html('Nome Obbligatorio');
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
return;
}
$.ajax({
type: "POST",
url: "../index.php",
dataType: "html",
data : { azione : 'inviaEmailCliente',
messaggio : messaggio,
oggetto : oggetto,
destinatario : destinatario,
nome : nome },
success:function(data){
dati = data.replace(/(\r\n|\n|\r)/gm,"");
if (dati.length > 0){
dati = dati.split('|');
if (dati[0] == '00'){
$('#contenutoInserimentoAna').html(dati[1]);
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalAnagrafica').modal('hide');
$('#nomeMail').val('');
$('#messaggioMail').val('');
$('#oggettoMail').val('');
location.reload();
});
}
if (dati[0] == '88'){
$('#contenutoInserimentoAna').html(dati[1]);
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalVarAnagrafica').modal('hide');
});
}
if (dati[0] == '99'){
$('#contenutoInserimentoAna').html(dati[1]);
$('#modalAnagrafica').modal('show');
$('#modalAnagrafica').on('hidden.bs.modal', function(){
$('#modalAnagrafica').modal('hide');
});
}
}
},
error:function (){
alert ('Errore di comunicazione con il server');
}
});
}
Html form of insert email, i don't paste the css...but hit is the form..
<input type="hidden" id="destinatarioMail" value="WRITE HERE THE ADRESS WHERE SENDS THE EMAIL{email} TO#EXAMPLE.COM" >
<div class="containerBorder padding3">
<div class="alert-warning">
<p><b>L'email sarà inviata a {email}</b></p>
</div>
<div class="row">
<div class="input-group">
<span class="input-group-addon testoBlu" id="nomeInvioMail">Nome *</span>
<input type="text" id="nomeMail" class="form-control" aria-describedby="nomeInvioMail" />
</div>
<div class="input-group">
<span class="input-group-addon testoBlu" id="oggettoInvioMail">Oggetto *</span>
<input type="text" id="oggettoMail" class="form-control" aria-describedby="oggettoInvioMail" />
</div>
<div class="input-group">
<span class="input-group-addon testoBlu" id="messaggioEmailCli">Messaggio Mail *</span>
<textarea class="form-control" id="messaggioMail" aria-describedby="messaggioEmailCli" style="max-width: 724px; max-height: 130px;"> </textarea>
</div>
</div>
<br>
<div align="center">
<input type="button" class="btn btn-danger" value="Invia" id="inviaEmailCli" onclick="inviaEmailCliente()" />
</div>
</div>
And this is the html for the modal
<div class="modal fade" id="modalAnagrafica" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabelAnagrafica">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary">
<h4 class="modal-title modalHeaderText" id="myModalLabelAnagrafica"><b>Anagrafica</b></h4>
</div>
<b><div class="modal-body" id="contenutoInserimentoAna">
</div></b>
<div class="modal-footer justify-content-center">
<div align="center">
<button class="btn btn-success btn-xs" data-dismiss="modal">Chiudi</button>
</div>
</div>
</div>
</div>
</div>

PHP Form: If a input field is empty then do not send the table data to mail

Here this form will not only send mail to me but also a duplicate copy to the user.And what I want to achieve is:
The entered data should be sent to mail in Html Table Format.
If an input field is empty then that table data should not be sent to emails. I also referred this link: (how to make if decision in swiftmailer to check if field is empty then do not send `td` to mail) but I didn't get this.
Note: I don't want all the fields to be required. Here I have given only name, email, and address fields as required in HTML, and the remaining fields are can be left empty and submit the form.
But for now, I am not getting any mail if I submit this form
Here is my PHP code:
<?php
if(isset($_POST['submit'])){
$to = "...#gmail.com"; // this is your Email address
$from = (!empty($_POST["email"])) ? '<tr><td>' . $_POST["email"] . '</td></tr>' : '';
$name = (!empty($_POST["name"])) ? '<tr><td>' . $_POST["name"] . '</td></tr>' : '';
$address = (!empty($_POST["address"])) ? '<tr><td>' . $_POST["address"] . '</td></tr>' : '';
$book_shelf = (!empty($_POST["book_shelf"])) ? '<tr><td>' . $_POST["book_shelf"] . '</td></tr>' : '';
$glass_ware = (!empty($_POST["glass_ware"])) ? '<tr><td>' . $_POST["glass_ware"] . '</td></tr>' : '';
$speakers = (!empty($_POST["speakers"])) ? '<tr><td>' . $_POST["speakers"] . '</td></tr>' : '';
$carpets = (!empty($_POST["carpets"])) ? '<tr><td>' . $_POST["carpets"] . '</td></tr>' : '';
$content = '<table>'.$name.$from.$address.$book_shelf.$glass_ware.$speakers.$carpets.'</table>';
$content2 = '<table>'.$name.$address.$book_shelf.$glass_ware.$speakers.$carpets.'</table>';
$headers = "From:" . $from;
$subject = "Form submission";
$headers2 = "From:" . $to;
$subject2 = "Copy of your form submission";
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
function add(id) {
var element = document.getElementById(id),
value = +element.value || 0;
element.value = value + 1;
}
function sub(id) {
var element = document.getElementById(id),
value = +element.value || 0;
value--;
if (value < 0) {
value = 0;
}
element.value = value;
}
HTML Code:
<form action="" method="post">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Enter E-Mail" name="email" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" rows="5" id="comment" placeholder="Address" name="address" required></textarea>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="range-label">
<label>Book Shelf</label>
</div>
<div class="range">
<a onClick="sub('book-shelf')"><i class="fa fa-minus-circle" aria-hidden="true"></i></a><input type="text" id="book-shelf" name="book_shelf"><a onClick="add('book-shelf')"><i class="fa fa-plus-circle" aria-hidden="true"></i></a>
</div>
</div>
<div class="col-md-3 col-sm-6">
<!--start-->
<div class="range-label">
<label>Glass Ware</label>
</div>
<div class="range">
<a onClick="sub('glass-ware')"><i class="fa fa-minus-circle" aria-hidden="true"></i></a><input type="text" id="glass-ware" name="glass_ware"><a onClick="add('glass-ware')"><i class="fa fa-plus-circle" aria-hidden="true"></i></a>
</div>
</div>
<!--end-->
<div class="col-md-3 col-sm-6">
<!--start-->
<div class="range-label">
<label>Speakers</label>
</div>
<div class="range">
<a onClick="sub('speakers')"><i class="fa fa-minus-circle" aria-hidden="true"></i></a><input type="text" id="speakers" name="speakers"><a onClick="add('speakers')"><i class="fa fa-plus-circle" aria-hidden="true"></i></a>
</div>
</div>
<!--end-->
<div class="col-md-3 col-sm-6">
<!--start-->
<div class="range-label">
<label>Carpets</label>
</div>
<div class="range">
<a onClick="sub('Carpets')"><i class="fa fa-minus-circle" aria-hidden="true"></i></a><input type="text" id="Carpets" name="carpets"><a onClick="add('Carpets')"><i class="fa fa-plus-circle" aria-hidden="true"></i></a>
</div>
</div>
<!--end-->
</div>
<!-- End of row --->
<input type="submit" name="submit" value="Submit">
</form>
You can check if the required values are set and are not empty, if they are set, then send the email.
You will need to set its headers so that it can be sent as HTML and not plain text. Also, here is a list of supported tags in an email template
//Set headers
$headers .= 'Content-type: text/html';
$headers2 .= 'Content-type: text/html';
if(
isset($_POST["email"]) && $_POST["email"] != "" &&
isset($_POST["name"]) && $_POST["name"] != "" &&
isset($_POST["address"]) && $_POST["address"] != ""
)
{
// If all required fields are set, then email them
mail($to,$subject,$content,$headers);
mail($from,$subject2,$content2,$headers2);
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
}
Add HTML required Attribute to your input fields as following example
function myFunction() {
var name = document.getElementById("usrname").value;
var city = document.getElementById("city").value;
if (city) {
alert(name + " " + city)
} else {
alert(name)
}
}
<form onsubmit="myFunction()">
Name: <input type="text" id="usrname" required><br> City: <input type="text" id="city"><br>
<input type="submit">
</form>

Categories

Resources