this is my contact form.
I need to display message in sweetalert after success/fail submission of form. The error/success message is in php alert.
<form class="contact-form" action="" method="post" id="form_id">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Full Name" required>
</div>
<div class="form-group">
<input type="number" name="number" class="form-control" placeholder="Phone No." required>
</div>
<div class="form-group">
<input type="text" name="country" class="form-control" placeholder="Country" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your Email Id" required>
</div>
<div class="form-group">
<input type="date" name="date" class="form-control" placeholder="Travel Date" required>
</div>
<div class="form-group">
<textarea class="form-control" name="message" placeholder="Your Message" style="height:140px"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="submit" value="send">SEND MESSAGE</button>
</form>
This is my php code
for send mail
use PHPMailer\PHPMailer\PHPMailer;
require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';
$mail = new PHPMailer(true);
$alert = '';
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$country = $_POST['country'];
$message = $_POST['message'];
$package=$_POST['package'];
$date=$_POST['date'];
try{
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = ''; // Gmail address which you want to use as SMTP server
$mail->Password = ''; // Gmail address Password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = '587';
$mail->setFrom(''); // Gmail address which you used as SMTP server
$mail->addAddress(''); // Email address where you want to receive emails (you can use any of your gmail address including the gmail address which you used as SMTP server)
$mail->isHTML(true);
$mail->Subject = 'Message Received';
$mail->Body = "<h3>Name : $name <br><br>Phone No: $number <br><br> Country: $country <br><br> Email: $email <br><br>Arrival Date: $date <br><br>Package: $package <br><br> Message: $message</h3>";
$mail->send();
$alert = 'alert-success';
} catch (Exception $e){
$alert = 'alert-error';
}
}
this is my javascript code
swal alert
is alert-success check
success:function(alert) {
if(alert == 'alert-success'){
swal("Good job!", "You clicked the button!", "success");
}
else swal("Something is missing!!!!!", "Try again","error");
}
if not using ajax you can do this :
<script>
var alert = '<?php echo $alert;?>';
if(alert == 'alert-success'){
alert('yes');//for test
swal("Good job!", "You clicked the button!", "success");
}
else if(alert=='alert-error'){
alert('no');//for test
swal("Something is missing!!!!!", "Try again","error");
}
</script>
you should have to be use ajax for this sweet alert operation.
$.ajax({
.... other settings you already have
error: function (xhr, ajaxOptions, thrownError) {
swal("success!", "Form has been submitted", "success");
}
});
Related
I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});
I've been trying to submit a form that is on my website but the form will not submit. I am not a php expert and I can not tell where my error is. The php file opens instead of sending to my two emails.
html
<form action="email.php" method="post" name="emailForm">
<div class="form-group">
<label for="Name"></label>
<input class="form-control name" placeholder="Name" id="Name" name="name">
</div>
<div class="form-group">
<label for="Email"></label>
<input class="form-control email" placeholder="Email" id="Email" name="email">
</div>
<div class="form-group">
<label for="Subject"></label>
<input class="form-control subject" placeholder="Subject" id="Subject" name="subject">
</div>
<div class="form-group">
<label for="Message"></label>
<textarea class="form-control Message" placeholder="Message" id="Message" name="message"></textarea>
</div>
<input type="submit" id="button" class="btn btn-default button_submit"></input>
</form>
and I have the php file in the main directory
and it contains
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$email_from = "georgestcm#gmail.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
$email_subject = "New Form submission";
$to = "georgestcm#gmail.com, yahwehown#gmail.com";
$email_body = "You have received a new message from the user $name.\n"."Here is the message:\n $message".
mail($to,$email_subject,$email_body,$headers);
?>
and my form validation is in in jquery. That is why I have not done it in php, because I am not a php expert.
jquery
$(document).ready(function() {
var name = $('input.name');
var email = $('input.email').prop('disabled',true);
var subject = $('input.subject').prop('disabled',true);
var message = $('textarea.Message').prop('disabled',true);
var button = $('input#button').prop('disabled',true);
name.on('keyup',function() {
if($(this).val().length > 0) {
email.prop('disabled',false);
} else {
email.prop('disabled',true);
}
});
email.on('keyup',function() {
if($(this).val().length > 0 && $(this).val().includes('#') && $(this).val().includes('.com')) {
subject.prop('disabled', false);
message.prop('disabled',false);
} else {
subject.prop('disabled', true);
message.prop('disabled',true);
button.prop('disabled',true);
}
});
message.on('keyup',function() {
if($(this).val().length > 0){
button.prop('disabled',false);
}
})
button.on('click', function() {
name.val('');
email.val('');
subject.val('');
message.val('');
})
})
I want to send email to my two emails.
Here is the HTML code:- https://pastebin.com/Rc3AGC8x
<html>
<body bgcolor="#ccccb3">
<script type="text/javascript">
function hello(min,max) {
var x;
x= Math.floor(Math.random()*(max-min+1)+min);
document.getElementById("complaint").value =x;
//document.write(x);
};
</script>
<center>
<form action="http://localhost/PHPMailer-master/" method="post">
<p>Name: <input id="n" placeholder="Name" name="n" required></p>
<p>E-Mail: <input id="e" placeholder="Email Address" type="email" name="e" required></p>
<p> <textarea id="m" placeholder="write your message here" name="m" rows="10" required></textarea></p>
<p><input id="mybtn" type="submit" value="Submit Form" onClick="hello(112,78945)"></p>
<input type="hidden" value="The complaint id is : #" id="complaint" name="complaint">
<!--<p>Clicks: <a id="clicks">0</a></p>-->
</form>
</center>
</body>
</html>
Here is the PHP code:- https://pastebin.com/g0Cnh8iR
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = '*******'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
if( isset($_POST['n']) && isset($_POST['e']) && isset($_POST['m']) ){
$n = $_POST['n'];
$e = $_POST['e'];
$m = nl2br($_POST['m']);
$c = $_POST['complaint'];}
else{
$n='';
$e='';
$m='';
$c='245';
}
$mail->setFrom('noreply#gmail.com', 'Panasonic');
$mail->addAddress('testpanasoniccontact#gmail.com', 'Pragzz'); // Add a recipient
//$mail->addAddress('ellen#example.com'); // Name is optional
//$mail->addReplyTo('info#example.com', 'Information');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Complaint Number: '.$c;
$mail->Body = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <p><b>Message: </b>'.$m.'</p>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent. Your complaint will be attended within 48 hours. Your complaint No. is '.$c;
}
?>
Password and username field has been deliberately removed.
The HTML Script contains a form field of the hidden type with Complaint as ID.
It is not able to fetch the value from javascript function and send to the php code.
try the below code. I have modified the JS part and also placed the hidden feild before the submit button. It working good now.
<html>
<body bgcolor="#ccccb3">
<center>
<form action="http://localhost/PHPMailer-master/" method="post">
<p>Name:<input id="n" placeholder="Name" name="n" required></p>
<p>E-Mail: <input id="e" placeholder="Email Address" type="email" name="e" required></p>
<p><textarea id="m" placeholder="write your message here" name="m" rows="10" required></textarea></p>
<input type="hidden" value="100" id="complaint" name="complaint">
<p><input id="mybtn" type="submit" value="Submit Form" onClick="hello(112,78945)"></p>
</form>
</center>
<script type="text/javascript">
function hello(min,max) {
var complaint = document.getElementById("complaint").value
console.log(complaint);
};
</script>
</body>
</html>
I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
Wish you all a happy 2015!
I have a simple contact us php form. I am validating it with parsley.js. The validation works fine but I am receiving a lot of spam mails.
I believe if I can force the form to be submitted only if Jquery is enabled, then it should solve my problem (right?).
I'm not an expert with PhP/ Jquery and any help will be appreciated.
Here is my PHP code
<?php
// Define Variables i.e. name tag, as per form and set to empty
$contact_name = $contact_email = $contact_phone = $contact_message = "";
// Sanitize data and use friendly names
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["contact_name"]);
$email = test_input($_POST["contact_email"]);
$phone = test_input($_POST["contact_phone"]);
$message = test_input($_POST["contact_message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Set values
$to = 'info#foryourservice.in';
$subject = 'New Message from Website';
$headers = 'From: info#domainname.com' . "\r\n" .
'Reply-To: info#domainname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Set Email content
$emailcontent = "A new message has been submitted from the website.
\n
Name : $name
Email : $email
Phone : $phone
Message : $message";
// Mail function
$send_contact=mail($to,$subject,$emailcontent,$headers);
if($send_contact){
header('Location: index.php#contactusform');
}
else {
echo "<script type='text/javascript'>alert('We encountered an ERROR! Please go back and try again.');</script>";
}
?>
Here is my HTML ( Im using Twitter Bootstrap)
<form role="form" method="POST" action="contactusform.php" id="contactusform" data-parsley-validate>
<div class="col-xs-6">
<div class="form-group" style="margin-bottom: -5px">
<label for="input1"></label>
<input type="text" name="contact_name" class="form-control" id="input1" placeholder="Name*" required data-parsley-required-message="Please enter your name">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input2"></label>
<input type="email" name="contact_email" class="form-control" id="input2" placeholder="Email Address*" data-parsley-trigger="change" required data-parsley-required-message="Please enter a valid Email address">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input3"></label>
<input type="tel" name="contact_phone" class="form-control" id="input3" placeholder="Phone Number*" required data-parsley-type="digits" data-parsley-minlength="10" data-parsley-maxlength="10" data-parsley-required-message="Please enter a 10 digit number">
</div>
<br>
<div class="form-group">
<button type="submit" id="contactbutton" class="btn btn-primary" style="background-color: #A8B645; border-color: transparent">Submit</button>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="input4"></label>
<textarea name="contact_message" class="form-control" rows="7" id="input4" placeholder="Message*" required required data-parsley-required-message="Say something!"></textarea>
</div>
</div>
</form>
This is what the Spam Email looks like :
A new message has been submitted from the website.
Name : お買い得アナスイ ミロード大壳り出しランキング
Email : rsilau#gmail.com
Phone : お買い得アナスイ ミロード大壳り出しランキング
Message : Shoppers takes the boast on bag
お買い得アナスイ ミロード大壳り出しランキング http://www.frkapaun.org/dyqfmnwg/ysl-annasuixmraAekm.asp
Add a hidden field to your form:
<input type="hidden" value="0" id="botcheck" name="botcheck" />
Then with jQuery set the value to 1:
$("#botcheck").val("1");
Then server-side check the value of $_POST["botcheck"].
You might want to check if your form is submitted using ajax:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Process form here
}
For further explanation