Contact form PHPMailer sending button is stuck loading - javascript

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.

Related

How to get the success message in the same page after submitting the form?

I'm trying to display a success and error message in the same page. What do i need to change?
The form is to send the data to the database and then show a success message in the same page, then redirect to another page. I've tried changing the ID value in the form and the java script, i still get the same results, the data is sent to the database, it redirects to another page, but it doesn't show the success message before redirecting.
Controller:
public function register_ajax() {
//form validation rules
$this->form_validation->set_rules('org_name', 'Organisation Name',
'trim|required');
$this->form_validation->set_rules('email', 'Email',
'trim|required|valid_email|is_unique[new_church.email]',
array('is_unique' => "This email address is already registered
with this application.")
);
$this->form_validation->set_rules('password', 'Your Password',
'trim');
$this->form_validation->set_rules('c_password', 'Confirm Password',
'trim|required|matches[password]',
array(
'matches' => 'Password does not match'
)
);
if ($this->form_validation->run()) {
$this->registration_model->update_church(); //insert the data
into db
echo 1;
redirect(site_url('registration/payment'));
} else {
echo validation_errors();
}
}
Model:
public function update_church() {
$org_name = ucwords($this->input->post('org_name', TRUE));
$email = $this->input->post('email', TRUE);
$password = ucfirst($this->input->post('password', TRUE));
$c_password = ucfirst($this->input->post('c_password', TRUE));
$data = array (
'org_name' => $org_name,
'email' => $email,
'password' => $password,
'c_password' => $c_password,
);
$this->db->insert('new_church', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
JavaScript:
//Registration
$('#registration_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'registration',
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>').fadeIn( 'fast' );
$('#registration_form')[0].reset(); //reset form fields
} else {
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
}
});
});
View:
<?php
$form_attributes = array("id" => "registration_form");
echo form_open('registration/register_ajax', $form_attributes); ?>
<div class="login100-form validate-form">
<div class="wrap-input100 validate-input" data-validate = "First
name is required">
<label class="form_header">Organisation Name</label>
<input class="input100" type="text" name="org_name" value="<?php
echo set_value('org_name'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid
email is required: ex#abc.xyz">
<label class="form_header">Your Work Email Address</label>
<input class="input100" type="email" name="email" value="<?php
echo set_value('email'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Password
is required">
<label class="form_header">Your Password</label>
<input class="input100" type="password" name="password" value="<?
php echo set_value('password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Confirm Password">
<label class="form_header">Confirm Password</label>
<input class="input100" type="password" name="c_password" value="<?php echo set_value('c_password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="text-center p-t-12">
<p>By clicking the button below, you agree to StreamApp's terms of acceptable use</p>
</div>
<div class="m-t-20">
<div id="status_msg"></div>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn"> NEXT </button>
</div>
</div>
<?php echo form_close(); ?>
I expect a success message to appear before redirecting to another page
what happened to your code is when your try to run the form validation it get always true because you set a condition where not executing if the result is true or false.
if ($this->form_validation->run() == TRUE) { //you should change it to this
$this->registration_model->update_church();
$data['success'] = 1;
} else { //if the form validation run false it will display the error.
$data['error'] = validation_errors();
}
echo json_encode($data);
And if you are going to send back a message to your AJAX code you should encode it first using JSON.
To display it.. do this.
if (msg.success == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>');
$('#registration_form')[0].reset(); //reset form fields
setTimeout(function(){
window.location.replace("<?php echo base_url('registration/payment') ?>");
}, 3000); //set it to your time
} else if(msg.error){
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg.error + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
Hope that helps.Let me know the result.
Remove this line:
redirect(site_url('registration/payment'));
And in your ajax success function add this:
if (response == "1") {
// todo set timeout maybe and show a success message then redirect.
window.location.href = siteUrl+"registration/payment";
}
And just make sure to define siteUrl in your js file:
const siteUrl = "http://localhost/";

Ajax not refreshing contact form (PHP and Bootstrap 4)

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>

Bootstrap Alert Message not working

First - Im not an expert in PHP, but just know how to make some basic changes within contact form using PHP.
On this contact form when I filled in the required textfields and hit the submit button it redirects to the contact.php with a Contact form successfully submitted. Thank you, I will get back to you soon! message instead of displaying the message inside the <div class="messages"></div> on request-interpreter.html
HTML (form)
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div> <----- displays alert messages
<div class="controls">
<div class="row-form">
<div class="col-md-6">
<p class="text-req"><strong>*</strong> These fields are required. </p>
</div>
</div>
<div class="row-form">
<div class="col-md-6">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="First name *" required="required" data-error="First name is required." tabindex="1">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="Email *" required="required" data-error="Your email address is required." tabindex="3">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row-form">
<div class="col-md-6">
<div class="form-group">
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Last name *" required="required" data-error="Last name is required." tabindex="2">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Phone *" required="required" data-error="Your phone number is required." tabindex="4">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row-form">
<div class="col-md-12">
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Leave a message for us *" rows="4" required="required" data-error="Your important message is required." tabindex="5"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-success btn-send" value="Send Request" tabindex="6">
</div>
</div>
</div>
</form>
contact.php
<?php
// an email address that will be in the From field of the email.
$from = 'Contact form';
// an email address that will receive the email with the output of the form
$sendTo = $_POST['email'];
// 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';
// 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'];
}
Alert message AJAX
$(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 = "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); <------ it should display the alert message, but its not working.
// empty the form
$('#contact-form')[0].reset();
}
}
});
}
})
});
You are echoing it (printing it) instead of returning the response, change it like this in your Contact.php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
return $encoded;
}
// else just display the message
else {
return $responseArray['message'];
}

Custom AJAX form not working async

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(){});

PHP, jQuery, Ajax, send HTML input fields with attachment field code not working

I am trying to send an email with an optional attachment when a button is clicked and display the results above the form fields. I have put together the following code, but it is not working (nothing happens when I click the submit button; would like to create a fiddle but JSFiddle does not accept PHP code):
Here is the HTML:
<div id="contactSubmitResult"></div>
<div id="contactSubmitResult"></div>
<div id="contactForm">
<div class="col1">
<label for="form_firstname">Firstname <span class="required">*</span></label>
<input type="text" id="form_firstname" name="form_firstname" value="" required />
</div>
<div class="col2">
<label for="form_lastname">Lastname <span class="required">*</span></label>
<input type="text" id="form_lastname" name="form_lastname" value="" required />
</div>
<div class="col1">
<label for="form_address">Address</label>
<input type="text" id="form_address" name="form_address" value="" />
</div>
<div class="col2">
<label for="form_city">City</label>
<input type="text" id="form_city" name="form_city" value="" />
</div>
<div class="col1">
<label for="form_email">Email <span class="required">*</span></label>
<input type="email" id="form_email" name="form_email" value="" required />
</div>
<div class="col2">
<label for="form_phone">Phone <span class="required">*</span></label>
<input type="tel" id="form_phone" name="form_phone" value="" required />
</div>
<div class="col12">
<label for="form_attachment">Add Attachment</label>
<input type="file" id="form_attachment" name="form_attachment" />
</div>
<div class="col12">
<label for="form_message">Message <span class="required">*</span></label>
<textarea id="form_message" name="form_message" required></textarea>
</div>
<div class="col12">
<input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
</div>
</div>
Here is the JavaScript:
<script type="text/javascript" src="http://jdoe.com/js/jquery-1.11.1.min.js"></script>
<!-- validate and submit form input -->
<script type="text/javascript">
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
var post_data = new FormData();
post_data.append('form_firstname', $('input[name=form_firstname]').val());
post_data.append('form_lastname', $('input[name=form_lastname]').val());
post_data.append('form_address', $('input[name=form_address]').val());
post_data.append('form_city', $('input[name=form_city]').val());
post_data.append('form_email', $('input[name=form_email]').val());
post_data.append('form_phone', $('input[name=form_phone]').val());
post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
post_data.append('form_message', $('textarea[name=form_message]').val());
// Ajax post data to server
$.ajax({
url: 'http://jdoe.com/sendContactFormEmail.php',
data: post_data,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
// display an animation with the form submission results
$(matchContactSubmitResult).hide().html(output).slideDown();
}
});
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
</script>
Here is the PHP code which receives the jQuery AJAX POST request:
<?php
//$output = json_encode(array('type'=>'error', 'text' => 'Yes'));
//die($output);
include("settings.php");
$boundaryString = "generateboundaryfromthis";
$to_email = "jdoe#gmail.com";
$from_email = "noreply#jdoe.com";
$replyTo_email = "noreply#jdoe.com";
if (isset($_POST)) {
// check whether this is an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array(
'type' =>' error',
'text' => 'Ajax POST request expected.'
));
die($output); //exit script outputting json data
}
// retrieve sanitized input data
$form_firstname = filter_var($_POST["form_firstname"], FILTER_SANITIZE_STRING);
$form_lastname = filter_var($_POST["form_lastname"], FILTER_SANITIZE_STRING);
$form_address = filter_var($_POST["form_address"], FILTER_SANITIZE_STRING);
$form_city = filter_var($_POST["form_city"], FILTER_SANITIZE_STRING);
$form_email = filter_var($_POST["form_email"], FILTER_SANITIZE_EMAIL);
$form_phone = filter_var($_POST["form_phone"], FILTER_SANITIZE_NUMBER_INT);
$form_message = filter_var($_POST["form_message"], FILTER_SANITIZE_STRING);
$email_body = <<<EOT
Firstname: $form_firstname
Lastname: $form_lastname
Address: $form_address
City: $form_city
E-mail: $form_email
Phone: $form_phone
Message:
$form_message
EOT;
// retrieve attached file
$hasAttachment = false;
if (isset($_FILES["form_attachment"])) {
$hasAttachment = true;
$fileTmpName = $_FILES["form_attachment"]['tmp_name'];
$fileName = $_FILES["form_attachment"]['name'];
$fileSize = $_FILES["form_attachment"]['size'];
$fileType = $_FILES["form_attachment"]['type'];
$fileError = $_FILES["form_attachment"]['error'];
$handle = fopen($fileTmpName);
$content = fread($handle, $fileSize);
fclose($handle);
$encodedContent = chunk_split(base64_encode($content));
}
if ($hasAttachment) {
// user submitted an attachment
$boundary = md5($boundaryString);
// header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $replyTo_email . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
// plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($email_body));
// attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $fileType; name=\"$fileName\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$fileName\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encodedContent;
} else {
// user did not submit an attachment
$headers = "From:" . $from_email . "\r\n" .
"Reply-To: " . $replyTo_email . "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $email_body;
}
$mailSentSuccessfully = mail($to_email, $subject, $body, $headers);
if ($mailSentSuccessfully) {
//$output = json_encode(array('type'=>'message', 'text' => $pageSettings->getContents("mailSentSuccess")));
$output = json_encode(array('type'=>'message', 'text' => 'Message sent.'));
die($output);
} else {
//$output = json_encode(array('type'=>'error', 'text' => $pageSettings->getContents("mailSentFailure")));
$output = json_encode(array('type'=>'error', 'text' => 'Error encountered. Message not sent.'));
die($output);
}
}
One problem: you forgot to put a html tag to
matchContactSubmitResult = "#contactSubmitResult";
add
<div id="contactSubmitResult"></div>
Here is snippet. I take the liberty to provide an alternative to success: function(){}, instead I used .done() and .fail() to provide in network or other problems. See here: jQuery.ajax() (I can't test your php code, but your jquery code works)
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
var post_data = new FormData();
post_data.append('form_firstname', $('input[name=form_firstname]').val());
post_data.append('form_lastname', $('input[name=form_lastname]').val());
post_data.append('form_address', $('input[name=form_address]').val());
post_data.append('form_city', $('input[name=form_city]').val());
post_data.append('form_email', $('input[name=form_email]').val());
post_data.append('form_phone', $('input[name=form_phone]').val());
post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
post_data.append('form_message', $('textarea[name=form_message]').val());
// Ajax post data to server
$.ajax({
url: 'http://jdoe.com/sendContactFormEmail.php',
data: post_data,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json'
}) .done(function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
$(matchContactSubmitResult).hide().html(output).slideDown();
}).
fail( function(response){
output = '<div class="error"> NetWork Problems</div>';
$(matchContactSubmitResult).hide().html(output).slideDown();
});
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contactForm">
<div class="col1">
<label for="form_firstname">Firstname <span class="required">*</span></label>
<input type="text" id="form_firstname" name="form_firstname" value="" required />
</div>
<div class="col2">
<label for="form_lastname">Lastname <span class="required">*</span></label>
<input type="text" id="form_lastname" name="form_lastname" value="" required />
</div>
<div class="col1">
<label for="form_address">Address</label>
<input type="text" id="form_address" name="form_address" value="" />
</div>
<div class="col2">
<label for="form_city">City</label>
<input type="text" id="form_city" name="form_city" value="" />
</div>
<div class="col1">
<label for="form_email">Email <span class="required">*</span></label>
<input type="email" id="form_email" name="form_email" value="" required />
</div>
<div class="col2">
<label for="form_phone">Phone <span class="required">*</span></label>
<input type="tel" id="form_phone" name="form_phone" value="" required />
</div>
<div class="col12">
<label for="form_attachment">Add Attachment</label>
<input type="file" id="form_attachment" name="form_attachment" />
</div>
<div class="col12">
<label for="form_message">Message <span class="required">*</span></label>
<textarea id="form_message" name="form_message" required></textarea>
</div>
<div class="col12">
<input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
</div>
</div>
<div id="contactSubmitResult"></div>
I've updated my code. There are no errors with the PHP code but when I
try to attach an attachment nothing happens. – John Sonderson
if so i think the problem is here.haven't tested but, this might help :)
var myfile=$('input[name=form_attachment]').val();
//apend the file
post_data.append('form_attachment', myfile);

Categories