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()
Related
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.
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 ) );
}
Im getting success from Ajax but not receiving the intended email and there does not seem to be anything wrong with the PHP. I have little experience with PHP, I need some way to get some feedback from the PHP.
Jquery
function PHP_EMAIL(name, email, message){
var emailInfo = [name,email,message];
$.ajax ({
type: "POST",
url:"the_php_file.php",
data: {email_info_array: emailInfo},
success: function(data) {
alert(data); <---alerts the entire php script back
alert("Email was successfuly sent!); <<<--- alerts success!
but no email recieved
}
});
}
PHP
$email_info = json_decode($_POST['email_info_array']);
$to = "my_email#gmail.com";
$subject = 'portfolio contact';
$user_name = $email_info[0];
$user_email = $email_info[1];
$message = $email_info[2];
$headers = "From: website.com";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "sent";
}
else
{
echo "fail";
}
HTML
<div class="site-contact-box site-text-20 site-text-grey-violet">
<!-- form -->
<form onsubmit="return false" id="emailform">
<div class="site-form-error">* You must fill all fields of the form *</div>
<br> Name <input type="text" name="name" value="" required> <div class="site-name-error site-text-12"> * invalid name </div>
<br> E-mail <input type="text" name="email" value="john.doe#example.com" required> <div class="site-email-error site-text-12"> * invalid email </div>
<br>
<div class="site-message-error site-text-12"> * message must be more than (8 characters) </div>
<br> <br> please leave a message...
<br> <p class="site-text-12"> (minimum 8 characters) <p>
<br>
<textarea rows="12" cols="50" name="message" form="emailform" required></textarea>
<br>
<div class="site-agree-error site-text-12"> you must agree to terms </div>
<br> <br>
<div class="site-agreement site-text-13 site-text-black">
* I agree to the Terms & Agreement <input type="checkbox" id="agree" required>
</div>
<br>
<input class="site-text-bold site-text-15" type="submit" name="submit" onclick="checkInput()">
</form>
</div>
<?php
header('Content-type: application/json');
echo json_encode($response_array);?>
query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
I am working on a website with an Ajax contact form. Tried a lot, it successfully sends a mail without headers below is my code please help me to fix this
code
<div class="form">
<div class="title">
<h2 class="orange"><span class="orange">Contact</span> US</h2>
</div>
<div class="height15"></div>
<div id="return_message"></div>
<div class="field">
<label>First Name:</label>
<input name="name" type="text" />
</div>
<div class="field">
<label>Phone Number:</label>
<input name="phone" type="text" />
</div>
<div class="field">
<label>Email Address:</label>
<input name="email" type="text" />
</div>
<label>Message:</label>
<textarea name="message" cols="" rows=""></textarea>
<div class="clear"></div>
<a class="org_btn more submit" id="submit" href="#.">Submit</a> </div>
<script language="javascript">
$(document).ready(function() {
$("#menu_btn").click(function(){
$("#sub_menu").slideToggle("slow");
});
//Contact us form validation
$('#return_message').hide();
$('#submit').click(function(event){
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var message = $('#message').val();
if( (name=='') || (phone=='') || (email=='') || (message=='') )
{
$('#name').addClass('error_active');
$('#phone').addClass('error_active');
$('#email').addClass('error_active');
$('#message').addClass('error_active');
}
else
{
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email))
{
alert("Please Enter valid email address");
$('#email').addClass('error_active');
}
else
{
$.ajax(
{
type: 'POST',
data: ({name : name, phone : phone, email : email, message : message}),
url: 'send_mail.php',
success: function(data)
{
if(data)
{
$('#return_message').show('slow').html("<p>Email has been sent...</p>");
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#message').val('');
$('#name').removeClass('error_active');
$('#phone').removeClass('error_active');
$('#email').removeClass('error_active');
$('#message').removeClass('error_active');
}
else
{
$('#return_message').show('slow').html("<p>Email has not been sent...</p>");
}
}
});
}
}
});
});
</script>
php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "info#kodspider.com"; // Please put your email addres.
$subject = "Marthoman Vidyapeedom"; //Please put subject of your email.
if($phone!='')
{
$message2 = $message.'\r\nPhone:'.$phone;
}
else
{
$message2 = $message;
}
$message = $message.'\r\nPhone:'.$phone;
$headers = "From: ".$email;
$sent = mail( $to, $subject, $message2, $headers );
if($sent)
{
echo "success";
}
else
{
echo "error";
}
?>
you have given
<input name="name" type="text" />
but in jquery your calling
$('#name').val('')
in jquery # selector is used only for id
make change
<input name="name" id="name" type="text" />
for more details in jquery read this
I have a PHP contact form here:
leongaban.com
Below is a screenshot showing the 500 (Internal Server Error) I'm getting after I click Submit
HTML form
<div class="the-form">
<form id="contact">
<div id="status"></div>
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" value="" tabindex="1">
</div>
<div>
<label for="email">Your Email</label>
<input type="text" name="email" id="email" value="" tabindex="2">
</div>
<div>
<label for="textarea">Message:</label>
<textarea cols="40" rows="8" name="comments" id="comments" tabindex="3"></textarea>
</div>
<div>
<input class="submit-button" id="submit" type="submit" value="Submit" tabindex="5">
</div>
</form><!-- #contact -->
</div><!-- .the-form -->
My Javascript
$(function(){
$('#submit').click(function(){
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val()
};
$.ajax({
url: "includes/send.php",
type: 'POST',
data: form_data,
success: function(status) {
if (status == 'success') {
$('#status').html('<h3 class="success">Thank You!</h3>')
.hide().fadeIn(2000);
} else {
$('#status').html('<p class="error">Both name and email are required fields.</p>')
.hide().fadeIn(2000);
}
} // end send contact form
}); //end ajax
return false;
}); //end send contact form click
});
My PHP
<?php
$name = $_POST['name'];
$email = trim($_POST['email']);
$comments = $_POST['comments'];
$error = array();
$site_owners_email = 'myEmail#gmail.com'; // Replace this with your own email address
$site_owners_name = 'Leon Gaban'; // replace with your name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
if (!$error) {
$response = 'success';
$subject = $name . ' needs help from CodePopper!';
$body = 'Codepopper,' . "\n\nName: " . $name .
"\nEmail: " . $email .
"\nComments: " . $comments;
require_once 'lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('hostname', 25)
->setUsername('username')
->setPassword('password')
;
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setSubject($subject);
$message->setFrom(array('myEmail#gmail.com' => 'leongaban.com'));
$message->setTo(array('myEmail#gmail.com' => 'Leon Gaban'));
$message->setBody($body);
$result = $mailer->send($message);
echo $response;
} # end if no error
else {
$response = 'error';
echo $response;
} # end if there was an error sending
I forgot to enter in my email host settings into my send.php file
$transport = Swift_SmtpTransport::newInstance('leongaban.com', 25)
->setUsername('my email')
->setPassword('my password');
Side note, I now have root access to my server :)