I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.
PHP
<?php
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "description" => true, "email" => true, "number" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
//header('Content-type: application/json');
//attempt to send email
$messageBody = constructMessageBody();
require 'php_mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress("example#example.com");
$mail->Subject = $_POST['name'];
$mail->Body = $messageBody;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted from PHP.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
(function($) {
$('#form').on('submit', function(){
event.preventDefault();
var contactFormUtils = {
clearForm: function () {
grecaptcha.reset();
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").append('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$('#submit-email').prop('disabled', true).html("sending");
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log('success');
$('#form').fadeOut(400)
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
console.log('error');
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
$('#submit-report').prop('disabled', false).html("Send message");
contactFormUtils.clearForm();
},
complete: function() {
console.log('complete');
}
});
return false;
});
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8 site-block">
<form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
<div id="feedbackSubmit"></div>
</div>
change
jQuery('#form').on('submit', function(){
to
jQuery('.ajax').on('submit', function(event){
and replace ALL $ with jQuery
and
wrap your code in document ready function
jQuery(function(){});
Related
I am trying to make this code work, and have tried many things (some of which I also found in StackOverflow), but nothing works. When I click on "Send Message" (submit button to send the contact info), absolutely nothing happens.
HTML:
<!-- CONTACT FORM -->
<form method="post" class="wow fadeInUp" id="contact-form">
<!-- IF MAIL SENT SUCCESSFUL -->
<h6 class="text-success">Your message has been sent successfully.</h6>
<!-- IF MAIL NOT SENT -->
<h6 class="text-danger">E-mail must be valid and message must be longer than 1 character.</h6>
<div class="col-md-6 col-sm-6">
<input type="text" class="form-control" id="cf-name" name="name" placeholder="Full name">
</div>
<div class="col-md-6 col-sm-6">
<input type="email" class="form-control" id="cf-email" name="email" placeholder="Email address">
</div>
<div class="col-md-12 col-sm-12">
<input type="text" class="form-control" id="cf-subject" name="subject" placeholder="Subject">
<textarea class="form-control" rows="6" id="cf-message" name="message" placeholder="Message"></textarea>
<button type="submit" class="form-control" id="cf-submit" name="submit">Send Message</button>
</div>
</form>
JS:
// CONTACT FORM
$("#contact-form").submit(function (e) {
e.preventDefault();
var name = $("#cf-name").val();
var email = $("#cf-email").val();
var subject = $("#cf-subject").val();
var message = $("#cf-message").val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "contact.php"
data: dataString,
success: function () {
$('.text-success').fadeIn(1000);
//$('.text-danger').fadeOut(500);
}
});
}
else {
$('.text-danger').fadeIn(1000);
//$('.text-success').fadeOut(500);
}
return false;
});
contact.php:
<?php
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['subject']) &&
isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
mail( "davidchau#gmail.com", "Contact Form: ". $_POST['name'], $_POST['subject'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
I have the JS script inside the body of the HTML (at the end of the body). Any help is greatly appreciated.
I have this exact code on another website and it works flawlessly but for some reason on this website it won't work. It sends the email but it refreshes the page and forwards it to a contact.php with a message.
I have read through everything I could find. I have gone over the code and nothing is different. I even changed the html button type from submit to button. Nothing is working. The last thing I tried was to copy and paste the code from the working website to this site, and still it refreshes the page.
The ajax codes is being loaded after the jquery.
html (index.html):
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages">
</div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">First Name *</label>
<input id="form_name" type="text" name="name" class="form-control" required="required"
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Last Name *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" required="required"
data-error="Lastname is required.">
<div class="help-block with-errors">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" required="required"
data-error="Valid email is required.">
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control">
<div class="help-block with-errors">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" rows="4" required="required"
data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-send" value="Send message">
</div>
</div>
</div>
</form>
php (contact.php)
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'Demo contact form <info#testing.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <info#testing.com>';
// subject of the email
$subject = 'New message from contact form';
// 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', 'message' => 'Message');
// 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'];
}
?>
ajax (contact.js)
$(function () {
$('#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 = "contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// 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('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
my javascript files are in the following order:
<script src="js/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
crossorigin="anonymous"></script>
<script type="text/javascript" src="./js/mdb.min.js"></script>
<!--validator-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
<!--contact.js-->
<script src="contact.js"></script>
Take out these changes:
Contact.php
// 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;
exit();
}
After echoing your json encoded array, it is important that you exit() the script else you won't end up with a proper JSON string on the client side;.
Contact.js
<script>
$(document).ready(function () {
$('.btn-send').on('click', function (e) {
e.preventDefault();
$('#contact-form').validator(); //Just make sure this works because I didn't work with it.
let url = "contact.php";
let formData = $("#contact-form").serialize();
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: formData, //You shouldn't use `this` inside this ajax scope if you are trying to refer to your form. It's better you call the form element by it's `id` here or reassign `this` before entering the ajax call scope.
success: function (data) {
// we recieve the type of the message: success x danger and apply it to the
let messageAlert = 'alert-' + data.type;
let messageText = data.message;
// let's compose Bootstrap alert box HTML
let 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('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
})
});
</script>
index.html
Everything thing is fine here. Just edit these lines:
<form id="contact-form" method="post" role="form">
<div class="col-md-12">
<input type="button" class="btn btn-send" value="Send message">
</div>
i have html, js and php files for contact form, but for some reason form is not responding and not sending emails.
I would appreciate your help.
JS/HTML
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_company = $('input[name=company-name]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userCompany': user_company,
'userSubject': user_subject,
'userMessage': user_message
};
// Ajax post data to server
$.post('/php/contact-me.php', post_data, function(response) {
// Load json data from server and output message
if (response.type == 'error') {
output = '<div class="error-message"><p>' + response.text + '</p></div>';
} else {
output = '<div class="success-message"><p>' + response.text + '</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Your Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Your Email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Email'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Company name -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="company" class="form form-control" placeholder="Company name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Company name'" name="company-name" data-name="Company Name">
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area"
required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message ></button>
</form>
and here is php file
<?php
if($_POST) {
$to_Email = "email#gmyemail; // Write your email here
// Use PHP To Detect An Ajax Request
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
// Exit script for the JSON data
$output = json_encode(
array(
'type'=> 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
// Checking if the $_POST vars well provided, Exit if there is one missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userSubject"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Input fields are empty!'));
die($output);
}
// PHP validation for the fields required
if(empty($_POST["userName"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> We are sorry but your name is too short or not specified.'));
die($output);
}
if(!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Please enter a valid email address.'));
die($output);
}
// PHP validation for the fields required
if(empty($_POST["userCompany"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> We are sorry but your name is too short or not specified.'));
die($output);
}
// To avoid the spammy bots, you can change the value of the minimum characters required. Here it's <20
if(strlen($_POST["userMessage"])<20) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Too short message! Take your time and write a few words.'));
die($output);
}
// Proceed with PHP email
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
$headers .= 'From: My website' . "\r\n";
$headers .= 'Reply-To: '.$_POST["userEmail"]."\r\n";
'X-Mailer: PHP/' . phpversion();
// Body of the Email received in your Mailbox
$emailcontent = 'Hey! You have received a new message from the visitor <strong>'.$_POST["userName"].'</strong><br/><br/>'. "\r\n" .
'His message: <br/> <em>'.$_POST["userMessage"].'</em><br/><br/>'. "\r\n" .
'<strong>Feel free to contact '.$_POST["userName"].' via email at : '.$_POST["userEmail"].'</strong>' . "\r\n" ;
$Mailsending = #mail($to_Email, $_POST["userSubject"], $emailcontent, $headers);
if(!$Mailsending) {
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Oops! Looks like something went wrong, please check your information one more time.'));
die($output);
} else {
$output = json_encode(array('type'=>'message', 'text' => '<i class="icon ion-checkmark-round"></i> Hello '.$_POST["userName"] .', Your message has been sent, we will get back to you asap !'));
die($output);
}
}
?>
If I add jQuery and change to .on("submit" of the form, it works.
$(document).ready(function() {
$("#contact-form").on("submit",function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_company = $('input[name=company-name]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userCompany': user_company,
'userSubject': user_subject,
'userMessage': user_message
};
// Ajax post data to server
$.post('/php/contact-me.php', post_data, function(response) {
// Load json data from server and output message
if (response.type == 'error') {
output = '<div class="error-message"><p>' + response.text + '</p></div>';
} else {
output = '<div class="success-message"><p>' + response.text + '</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Your Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Your Email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Email'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Company name -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="company" class="form form-control" placeholder="Company name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Company name'" name="company-name" data-name="Company Name">
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area"
required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message ></button>
</form>
It seems you have a syntax error in your PHP code
$to_Email = "email#gmyemail; // Write your email here
It should change to $to_Email = "email#gmyemail"; // Write your email here
BTW, if it's not the issue, Please enable PHP debug mode and check the error logs. This may help you to find the issue.
This is my code for a form. I am asking user to input email and password and checking if user is registered or not. If he is registered then I alert success:
<form role="form" class="legacy-form" action="" method="POST" id="myform1">
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="email" name="email" id="loginemail" class="form-control" placeholder="Email Address" required>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="password" name="password" id="loginpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="row" style="padding:15px">
<div class="col-xs-6 col-sm-3 col-md-3 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-primary" id="loginbtn">
</div>
</div>
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="form-group">
<input type="submit" value="Cancel" class="btn btn-danger" data-dismiss="modal">
</div>
</div>
</div>
</form>
This is the php code wherein the connection is placed in another file 'init.php'
<?php
include('init.php');
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result) {
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
echo json_encode(array("server_response"=>$response));
} else {
echo "error";
}
mysqli_close($con);
}
?>
this is my js file. On printing info in console I get Connection sucess{"server_response":[{"Count":"1","name":"sagar"}]}
$("#loginbtn").click(function(e) {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
check_for_user(loginemail, loginpassword);
function check_for_user(loginemail, loginpassword) {
console.log("in check_for_user");
var i = 0;
console.log(i);
i++;
var c = "";
var x = "1";
var user = "";
var formdata = {
loginemail: loginemail,
loginpassword: loginpassword
}
$.ajax({
url: 'getData.php',
type: "POST",
data: formdata,
dataType: 'text',
success: handle_success,
error: handle_error
});
function handle_success(info) {
console.log(info);
var obj = jQuery.parseJSON(info);
console.log(obj);
$(obj.server_response).each(info, function(index, value) {
user = value.name;
c = value.Count;
});
console.log(c);
console.log(user);
if (x == c) {
alert("Welcome");
//document.location='online.html';
} else {
alert("Enter valid username and password");
}
}
function handle_error() {
alert("error");
}
}
});
The flow of the code is like when the #loginbtn is clicked it posts loginemail and loginpassword on php and then it checks in database whether there is an identical entry in database, if yes it alerts "welcome". I have searched a lot on StackOverflow I found that it says there is error in either parsing JSON or in decoding it.
It looks like you are echoing "Connection success" in init.php although we can't see that.
A json response should have no other content in response ... just the json.
I'm having trouble with my contact form. I'm using the code from jon bake. However I can't get it to work, it's not sending the mail (or I'm not receiving it) and I don't even get the "success" message after pressing 'send'. This is how it looks in the 'console'.
I also get
HTTP500 : Server Error - Failed to execute request because the server encountered an unexpected condition .
( XHR ) : POST -
from console.
HTML
<form role="form" id="feedbackForm" method = "post" data-toggle="validator" data-disable="false">
<div class="form-group">
<label class="control-label" for="name">Name *</label>
<div class="input-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter your name.</span>
</div>
<div class="form-group">
<label class="control-label" for="phone">Phone</label>
<input type="tel" class="form-control optional" id="phone" name="phone" placeholder="Enter your phone (Optional)"/>
<span class="help-block" style="display: none;">Please enter a valid phone number.</span>
</div>
<div class="form-group">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="email">Email Address *</label>
<div class="input-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="message">Message *</label>
<div class="input-group">
<textarea rows="5" cols="30" class="form-control" id="message" name="message" placeholder="Enter your message" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LfIxCQTAAAAAK7ZBb9liJNpaebx12UbmOfiqtl9"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<span class="help-block" style="display: none;">Please enter a the security code.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-primary btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback</button>
</form>
</div><!--/span-->
</div><!--/row-->
<hr>
</div><!--/.container-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="assets/vender/intl-tel-input/js/intlTelInput.min.js"></script>
<script src="assets/js/contact-form.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
The contact-form.js
(function () {
//using regular expressions, validate email
var contactFormUtils = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9] {2,4})+$/;
return regex.test(email);
},
//if no form errors, remove or hide error messages
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
//upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
clearForm: function () {
$('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
$('#feedbackForm input,textarea').val("");
grecaptcha.reset();
},
//when error, show error messages and track that error exists
addError: function ($input) {
var parentFormGroup = $input.parents('.form-group');
parentFormGroup.children('.help-block').show();
parentFormGroup.addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$(document).ready(function() {
if ($("#phone").intlTelInput) {
$("#phone").intlTelInput({validationScript: "assets/vender/intl-tel- input/js/isValidNumber.js"});
$(".intl-tel-input.inside").css('width', '100%');
}
$("#feedbackSubmit").click(function() {
var $btn = $(this);
$btn.button('loading');
contactFormUtils.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
//use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
var $form = $("#feedbackForm"),
hasErrors = false;
if ($form.validator) {
hasErrors = $form.validator('validate').hasErrors;
} else {
$('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
hasErrors = true;
contactFormUtils.addError($(this));
}
});
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
var $phone = $('#phone');
if ($phone.val() && $phone.intlTelInput && !$phone.intlTelInput("isValidNumber")) {
hasErrors = true;
contactFormUtils.addError($phone.parent());
}
}
//if there are any errors return without sending e-mail
if (hasErrors) {
$btn.button('reset');
return false;
}
//send the feedback e-mail
$.ajax({
type: "post",
url: "../../library/sendmail.php",
data: $form.serialize(),
success: function(data) {
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
},
complete: function() {
$btn.button('reset');
}
});
return false;
});
$('#feedbackForm input, #feedbackForm textarea').change(function () {
var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
if ($(this).val()) {
checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
} else {
checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
}
});
});
})();
And the PHP
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "email" => true, "message" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
header('Content-type: application/json');
//do Captcha check, make sure the submitter is not a robot:)...
$url = 'https://www.google.com/recaptcha/api/siteverify';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(array('secret' => '6LfIxCQTAAAAABhWEJuLVdzE9m_-cwbBs9lM1xVi', 'response' => $_POST["g-recaptcha-response"]))
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($url, false, $context, -1, 40000));
if (!$result->success) {
errorResponse('reCAPTCHA checked failed!');
}
//attempt to send email
$messageBody = constructMessageBody();
require_once './vender/php_mailer/PHPMailerAutoload.php';
include_once './vender/php_mailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPDebug = 2
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "gmail.com";
$mail->Password = "password";
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress "gmail.com";
$mail->Subject = "Contact Form";
$mail->Body = $message_body;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
I'm very new to JavaScript and PHP so maybe I've missed something but I've tried to find a solution on Google but not been able to find one.
I hope I've made myself clear, thanks.