My form is supposed to show an alert, either "success" if the message was sent successfully or "danger" if there was an error, for example incorrect captcha or captcha completion.
The problem is that it doesn't show the alert with the CSS style, it only shows the close button and the error. Could someone tell me what is wrong?
Bootstrap version: 4.1 && PHP version 8.1
HTML:
<form id="contact_form" class="contact-form" action="contact_form/contact_form.php" method="post">
<div class="messages"></div>
<div class="controls two-columns">
<div class="fields clearfix">
<div class="left-column">
<div class="form-group form-group-with-icon">
<input id="form_name" type="text" name="name" class="form-control" placeholder="" required="required" data-error="Write your name.">
<label>Name</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group form-group-with-icon">
<input id="form_email" type="email" name="email" class="form-control" placeholder="" required="required" data-error="Put your email.">
<label>Email</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group form-group-with-icon">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="" required="required" data-error="Write a Subject.">
<label>Subject</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="right-column">
<div class="form-group form-group-with-icon">
<textarea id="form_message" name="message" class="form-control" placeholder="" rows="7" required="required" data-error="And... your message?."></textarea>
<label>Message</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6Lc9oSQcAAAAAMd-JXG26NP1iNzIeNZatd_Eetrv"></div>
<input type="submit" class="button btn-send" value="Send">
</div>
</form>
Code JS:
$(function () {
$('#contact_form').validator();
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact_form/contact_form.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();
}
}
});
return false;
}
});
});
CODE PHP:
<?php
// configure
$from = ''; // Replace it with Your Hosting Admin email. REQUIRED!
$sendTo = ''; // Replace it with Your email. REQUIRED!
$subject = '';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message'); // array variable name => Text to appear in the email. If you added or deleted a field in the contact form, edit this array.
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '';
//get verify response data
$c = curl_init('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$verifyResponse = curl_exec($c);
$responseData = json_decode($verifyResponse);
if($responseData->success):
try
{
$emailText = nl2br("You have new message from Contact Form\n");
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= nl2br("$fields[$key]: $value\n");
}
}
$headers = array('Content-Type: text/html; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $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['message'];
}
else:
$errorMessage = 'Robot verification failed, please try again.';
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
endif;
else:
$errorMessage = 'Please click on the reCAPTCHA box.';
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
endif;
Thanks in advance.
Related
So I have tried searching for this issue and have tried many fixes but I still keep getting the same issue, "Contact form successfully submitted. Thank you, I will get back to you soon!" displays on php page rather than on the contact form html page, Im sure there is something very simple that I'm missing, I keep ending in stupid thought and search loops, I thank you all for any help you can offer.
$(function() {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$("#contact-form").validator();
// when the form is submitted
$("#contact-form").on("submit", function(e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "ebsg.php";
// FOR CODEPEN DEMO I WILL PROVIDE THE DEMO OUTPUT HERE, download the PHP files from
// https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
var messageAlert = "alert-success";
var messageText =
"Your message was sent, thank you. ebgs will get back to you soon.";
// let's compose Bootstrap alert box HTML
var alertBox =
'<div class="alert ' +
messageAlert +
' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
messageText +
"</div>";
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$("#contact-form").find(".message").html(alertBox);
// empty the form
$("#contact-form")[0].reset();
}
return false;
}
});
});
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '6LelY04iAAAAAN',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
// configure
$from = 'ebsg contact form <ebsg#domain.com>';
$sendTo = 'ebsg contact form <email#yahoo.co.uk>';
$subject = 'ebsg contact form message';
$fields = array('name' => 'Name', 'surname' => 'Address', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from ebsg website contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $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['message'];
}
}
?>
<form id="contact-form" method="post" action="ebsg.php" role="form">
<div class="controls">
<div class="row">
<div class="col-md-6">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required>
</div>
<div class="col-md-6">
<label for="form_lastname">Address *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your address *" required>
</div>
<div class="col-md-6">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required>
</div>
<div class="col-md-6">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
</div>
<div class="col-md-12">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for EBSG *" rows="4" required></textarea>
</div>
<div class="col-md-6">
<div class="message"></div>
<div class="g-recaptcha" data-sitekey="6Lel478655677AACWfJGw0i2SDE9B-dbr-5mD6OHqG"></div>
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
<div class="col-md-6">
<p class="text-muted justify-content-center"><strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>
I have a form which I'm trying to use Recaptcha on.
I finally wound up just going with this one, which looked almost exactly as my form and PHP files did originally (so that seemed easy enough). Unfortunately, whether Recaptcha checkbox is clicked or not, the "Please check the recaptcha box" error pops up, indicating that it isn't working.
Here is the HTML:
<form class="contact__form" method="post" action="mail.php">
<!-- form message -->
<div class="row">
<div class="col-12">
<div class="contact__msg" style="display: none">
<p>Your message was sent successfully.</p>
</div>
</div>
</div>
<!-- end message -->
<!-- form element -->
<div class="row">
<div class="col-md-6 form-group">
<input name="name" type="text" class="form-control" placeholder="Name" required>
</div>
<div class="col-md-6 form-group">
<input name="email" type="email" class="form-control" placeholder="Email" required>
</div>
<div class="col-md-6 form-group">
<input name="phone" type="text" class="form-control" placeholder="Phone" required>
</div>
<div class="col-12 form-group">
<textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
</div>
<div class="col-12 form-group">
<div class="g-recaptcha" data-sitekey="6LfrrScdAAAAAM9UdXgQL4bHsISIEtYKW3Yca2Xm"></div>
</div>
<div class="col-12">
<input name="submit" type="submit" class="btn btn-success" value="Send Message">
</div>
</div>
<!-- end form element -->
</form>
PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// access
$secretKey = '....';
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo 'Please check the captcha form';
exit;
}
# FIX: Replace this email with recipient email
$mail_to = "...#domain.tld";
# Sender Data
$subject = "...";
$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
# Set a 400 (bad request) response code and exit.
http_response_code(400);
echo 'Please complete the form and try again';
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 'Please check the the captcha form.';
} else {
# Mail Content
$content = "Name: $name\n";
$content .= "Email: $email\n\n";
$content .= "Phone: $phone\n";
$content .= "Message:\n$message\n";
# email headers.
$headers = "From: $name <$email>";
# Send the email.
$success = mail($mail_to, $subject, $content, $headers);
if ($success) {
# Set a 200 (okay) response code.
http_response_code(200);
echo 'Thank You! Your message has been sent';
} else {
# Set a 500 (internal server error) response code.
http_response_code(500);
echo 'Oops! Something went wrong, we couldnt send your message';
}
}
} else {
# Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo 'There was a problem with your submission, please try again.';
}
?>
And finally, the JS file which is being called in the HTML file with the form:
(function ($) {
'use strict';
var form = $('.contact__form'),
message = $('.contact__msg'),
form_data;
// Success function
function done_func(response) {
message.fadeIn()
message.html(response);
setTimeout(function () {
message.fadeOut();
}, 5000);
form.find('input:not([type="submit"]), textarea').val('');
}
// fail function
function fail_func(data) {
message.fadeIn()
message.html(data.responseText);
setTimeout(function () {
message.fadeOut(5000);
}, 5000);
}
form.submit(function (e) {
e.preventDefault();
form_data = $(this).serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form_data
})
.done(done_func)
.fail(fail_func);
});
})(jQuery);
that API want POST data, not GET data. for example with hhb_curl i use i've like
$captcha_response = (new hhb_curl ( 'https://www.google.com/recaptcha/api/siteverify', true ))->setopt_array ( array (
CURLOPT_POSTFIELDS => array (
'secret' => '...',
'response' => $_POST ['g-recaptcha-response'],
'remoteip' => $ip
)
) )->exec ()->getResponseBody ();
$captcha_response = json_decode ( $captcha_response, true , 999, JSON_THROW_ON_ERROR);
if($captcha_response ['success'] !== true) {
http_response_code ( 400 );
header ( "content-type: text/plain;charset=utf8" );
die ( 'reCaptcha error!: ' . hhb_return_var_dump ( $captcha_response ) );
}
I was wondering someone could help me out with a best practice to achieve the following.
Please bare in mind I have very little experience with PHP, and am doing something more of a favour for a friend's company (his current developer is travelling and not due back until March).
He's put together 3 basic landing pages (each relevant to an industry), each has the exact same form on. The problem at the moment is the way they work is they all post to the same email address and have the same subject line (they all post to contact.php).
So what I'd like to do is add an IF statement, and perhaps put output a different $subject and $sendTo so they can be unique depending on each form. I've been having a look around and don't really want to have to create a new form and implement that, hopefully, I can just adjust what's here.
Here's contact.php
<?php
// an email address that will be in the From field of the email.
$from = 'Contact form <creative#email.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Contact form <creative#email.com>';
// subject of the email
$subject = 'Contact form enquiry from the Creative Services Landing Page';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'marketing' => 'Marketing');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
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 just display the message
else {
echo $responseArray['message'];
}
And here's the HTML
<form class="container" id="contact-form" method="post" action="contact.php" role="form">
<div class="row justify-content-md-center">
<div class="col-12 col-md-5 col-lg-4">
<div class="messages"></div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Your first name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Your surname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="A valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-12 col-md-3 col-lg-2">
<button type="submit" class="btn btn--primary">Send</button>
</div>
</div>
</form>
Any help would be hugely appreciated!
You could give to every form a different value via $_GET:
<form class="container" id="contact-form" method="post" action="contact.php?landing_page=1" role="form">
And then depending of $_GET['landing_page'] value set $from, $sendTo and $subject variables:
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'marketing' => 'Marketing');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
if (isset($_GET['landing_page']))
{
if ($_GET['landing_page'] == 1)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
elseif($_GET['landing_page'] == 2)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
elseif($_GET['landing_page'] == 3)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
else
{
throw new \Exception('Invalid landing_page value');
}
}
else
{
throw new \Exception('Invalid landing_page value');
}
/*
* LET'S DO THE SENDING
*/
I have the following form which sends its data to a php file which then processes the data and emails it to me. The problem is that I'm trying to upload a document along with the multipart form and it's not working. It sends the email just without the attachment. The weird thing is it used to work, but I'm not sure what I changed. $_FILES in the PHP form is always empty now, which suggests a problem with my html and not the PHP. I have been through the possible solutions in this link, but none of them worked for me. Can anyone see what's wrong with this form?
<form id="pre-register-contact-form" action="preregisterform.php" method="post" enctype="multipart/form-data" role="form">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<label for="name">Name*</label>
<input required="required" name="name" type="text" class="form-control" id="name" placeholder="Enter your full name" data-error="Please make sure you've entered your name.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="age">Age</label>
<input name="age" type="number" class="form-control" id="age" placeholder="Enter your age">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="email">Email address*</label>
<input required="required" name="email" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter your email address" data-error="Please make sure you've entered your email address.">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="phone">Phone Number</label>
<input name="phone" type="tel" class="form-control" id="phone" aria-describedby="phoneHelp" placeholder="Enter your phone number">
<small id="phoneHelp" class="form-text text-muted">We'll never share your phone number with anyone else.</small>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="comments">Comments</label>
<textarea name="comments" class="form-control" id="comments" placeholder="Add anything extra that you'd like to tell us about yourself here." rows="3"></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="cv">Upload CV*</label>
<input required="required" name="cv" type="file" accept=".pdf,.doc,.docx" class="form-control-file" id="cv" data-error="Please make sure you've uploaded a CV.">
<small id="cvHelp" class="form-text text-muted" aria-describedby="cvHelp">Please make sure it is in PDF or Word format.</small>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LcxSDgUAAAAAEM5qhjSDGS-Vu9HJSzLiL7yaAIG"></div>
</div>
<input type="submit" class="btn btn-success btn-send" value="Submit">
</div>
</form>
My PHP file is as follows (sensitive info removed):
<?php
// require ReCaptcha class
require('../elements/recaptcha/recaptcha-master/src/autoload.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once('../elements/mail/PHPMailer.php');
require_once('../elements/mail/Exception.php');
require_once('../elements/mail/SMTP.php');
$mail = new PHPMailer(true);
// configure
$sendTo = 'an_email_address_here';
$subject = 'New Pre-Register Contact Form Email';
$fields = array('name' => 'Name', 'age' => 'Age', 'phone' => 'Phone', 'email' => 'Email', 'comments' => 'Comments', 'cv' => 'CV'); // array variable name => Text to appear in the email
$okMessage = 'Thank you for your message. We will be in touch when the right vacancy for you comes up.';
$errorMessage = 'There was an error submitting the form. Please make sure your details are correct and try again.';
$recaptchaSecret = 'Some_alphanumeric_value_here';
// let's do the sending
try
{
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key in the config above
// from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
//Server settings
//$mail->SMTPDebug = 2; // 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 = 'some_email_address_here'; // SMTP username
$mail->Password = 'a_password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom("an_email_address", "Some_Name");
$mail->addReplyTo($_POST["email"], $_POST["name"]);
$mail->addAddress('an_email_address', 'some_name'); // Add a recipient
// This bit is always false
if (array_key_exists('cv', $_FILES)) {
$file_type = $_FILES['cv']['type'];
if (($file_type != 'application/pdf' || $file_type != 'application/msword')) {
throw new \Exception("Please make sure you are only uploading a PDF or a Word document.");
}
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['cv']['name']));
$file_name = $_FILES['cv']['name'];
$file_size = $_FILES['cv']['size'];
$file_error = $_FILES['cv']['error'];
if (move_uploaded_file($_FILES['cv']['tmp_name'], $uploadfile)) {
$mail->addAttachment(
$uploadfile,
$file_name,
'base64',
$file_type
);
}
}
$emailText = "";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "<b>$fields[$key]:</b> $value<br>";
}
}
$emailText .= "<br><br><span style=\"font-size: 12px; color: grey;\">Email sent via the careers pre-register contact form.</span><br>";
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $emailText;
$mail->AltBody = $emailText;
$mail->send();
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $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['message'];
}
EDIT
Just remembered I am using AJAX with the form! Here is the JQuery, I think this is causing the problem:
$('#pre-register-contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "preregisterform.php";
$.ajax({
type: "POST",
url: url,
contentType: false,
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) {
$('#pre-register-contact-form').find('.messages').html(alertBox);
$('#pre-register-contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
When you upload a file with ajax you should use Formdata like this:
$('#pre-register-contact-form').on('submit', function (e) {
var this = $(this);
if (!e.isDefaultPrevented()) {
var url = "preregisterform.php";
$.ajax({
type: "POST",
url: url,
data: new FormData(this),
dataType:'json',
processData: false,
contentType: false,
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) {
$('#pre-register-contact-form').find('.messages').html(alertBox);
$('#pre-register-contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
You can find more detailed information here about how to send/upload files with ajax
Db Connection
$server = 'localhost:8080';
$username = 'root';
$password = '';
$database = 'resort';
$connect = mysqli_connect($server, $username, $password ) or die(mysqli_error.'error connecting to db');
//select database
mysqli_select_db ($database, $connect) or die(mysqli_error.'error selecting db');
if(!empty($_POST)){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
if(!empty($name) && !empty($email) && !empty($message))
{
//insert the data into DB
mysql_query("INSERT into contactform (contact_id, contact_name, contact_email, contact_phone, message )
VALUES ('', '".$name."',
'".$email."', '".$phone."',
'".$message."' )") or die(mysqli_error());
//prepare email headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=isoo-8859-1\r\n";
$headers .= "From: ".$email."\r\n";
$to = 'mahesh.gulve004#gmail.com,'.$email;
$subject = 'Contact Form';
$body = 'From: <br/> Name: '.$name.' <br/>E-mail: '.$email.'<br/>Phone: '.$phone.'<br/>Message: '.$message;
//before sending the email make sure that the email address is correct
if ( $filtered_email == false ) {
echo json_encode(array(
'error' => true,
'msg' => "The email address entered it's not correct!"
));
exit;
}
$mail = mail($to, $subject, $body, $headers);
//finally send the email
if ( $mail ) {
//finally send the ajax response
echo json_encode(array(
'error' => false
));
exit;
} else {
//finally send the ajax response
echo json_encode(array(
'error' => true,
'msg' => "Opss...Something went wrong. Message was not sent!"
));
exit;
}
} else {
echo json_encode(array(
'error' => true,
'msg' => "You haven't completed all required fileds!"
));
exit;
}
}
$(function() {
//CONTACT FORM AJAX SUBMIT
$('#send').click(function() {
$.ajax({
url: 'mailer.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log(data);
if (data.error === true) {
$('#error').css('display', 'block');
var error = document.getElementById('error');
error.innerHTML = data.msg;
setTimeout(function() {
window.scrollTo(0, 1);
}, 100);
} else {
$('#note').show();
$('#error').hide();
$("#fields").hide();
}
}
});
return false;
});
});
<div class="col-md-6">
<div id="test-form" class="white-popup-block mfp-hide" style="width:400px;float:left;">
<div id="formcontent">
<div id="formheader" style="border-bottom:1px solid #e3e3e3;margin-bottom:20px;">
<h1 style="color:#37bc9b;font-size:33px;">We will get back to you...</h1>
</div>
<fieldset style="border:0;">
<div id="note">
<h2>Message sent successfully!</h2>
</div>
<div class="contact-form">
<form id="contactForm" method="post" action="">
<div class="form-group">
<label for="name">Name</label>
<span id="name-info" class="info">
<input type="text" placeholder="" id="name" name="name" class="form-control demoInputBox">
</div>
<div class="form-group">
<label for="email">Email</label>
<span id="email-info" class="info">
<input type="text" placeholder="" id="email" name="email" class="form-control demoInputBox">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<span id="phone-info" class="info">
<input type="text" id="phone" name="phone" class="form-control demoInputBox">
</div>
<div class="form-group">
<label for="message">Message</label>
<span id="message-info" class="info">
<textarea placeholder="" rows="5" id="message" name="message" class="form-control demoInputBox">
</textarea>
</div>
<input class="btn btn-info" id="send" type="submit" value="Submit"/>
</form>
</div>
</fieldset>
</div>
</div>
</div>
<div id="error"></div>
Issue is that when I click on submit the data is not submitted in fact I will say nothing happens by clicking submit button. Errors does not occur so no way to find out what the problem is. I am trying to build a contact form that can send mail. So you will also get some code related to it.
To submit the form you should use:
$('#contactForm').submit(function(){
//your ajax function
return false;
});
try $("#contactForm").serialize() instead of $(this).serialize()