Ajax not refreshing contact form (PHP and Bootstrap 4) - javascript

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>

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/";

Why is form submit message displaying all characters from my index.html file?

When my message is submitted it goes to my email address and works fine, but the message success notification doesn't display 'Your message was sent successfully.', instead it displays all of the lines of code within my index file.
I think it has something to do with style="display: none".
Any idea how to show the 'Your message has been sent' message?
index.html
<div class="col-lg-5 mx-auto">
<div class="contact-form">
<div class="container">
<form class="contact-form" method="post" action="mail.php">
<!-- form message -->
<div class="row">
<div class="col-lg-12">
<div class="alert alert-success contact__msg" style="display: none" role="alert">
Your message was sent successfully.
</div>
</div>
</div>
<!-- end message -->
<!-- form element -->
<div class="form-group">
<label><strong>Name</strong></label>
<input name="name" type="text" class="form-control" placeholder="Enter Name" required>
</div>
<div class="form-group">
<label><strong>Email</strong></label>
<input name="email" type="email" class="form-control" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label><strong>Message</strong></label>
<textarea name="message" class="form-control" rows="3" placeholder="Enter Message" required></textarea>
</div>
<button name="submit" type="submit" class="btn btn-default"><span class="fa fa-paper-plane"></button></span>
<!-- end form element -->
</form>
</div>
</div>
mail.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
# FIX: Replace this email with recipient email
$mail_to = "*myemail*#gmail.com";
# Sender Data
$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) 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;
}
# Mail Content
$content = "Name: $name\n";
$content .= "Email: $email\n\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 couldn't 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.";
}
?>
main.js
(function ($) {
'use strict';
var form = $('.contact-form'),
message = $('.contact__msg'),
form_data;
// Success function
function done_func(response) {
message.fadeIn().removeClass('alert-danger').addClass('alert-success');
message.text(response);
setTimeout(function () {
message.fadeOut();
}, 100000);
form.find('input:not([type="submit"]), textarea').val('');
}
// fail function
function fail_func(data) {
message.fadeIn().removeClass('alert-success').addClass('alert-success');
message.text(data.responseText);
setTimeout(function () {
message.fadeOut();
}, 100000);
}
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);
Check the success function you specify the response but not the text to display.
e.g: message.text(response.??);
The field that contains the message from the back end script is not included so I’m guessing the issue is here. display:none is not the issue...

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'];
}

Form submission success message not displaying

I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}

Contact form doesn't validate inside bootstrap modal

So I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine when placed on a page, however when I place it inside a bootstrap popup modal, the validator doesn't work. If all fields are empty and submit button hit, it will say 'message sent' even though it did not send, and if you fill in the fields it will still send and give success message also.
Also, if I hit the button to open modal as soon as page loads but before the script has loaded, it will work, so it's obviously because the modal is not visible when the validator script loads, so it misses it.
If anyone has some answers it would be super helpful as I'm pretty new to PHP and JS!
Here is my modal HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<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_email">Email *</label> <input class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<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 class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>
This is my PHP file
<?php
// configure
$from = '<mail#myemail.net>';
$sendTo = 'Demo contact form <mail#myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail#myemail.net' . "\r\n" ;
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($email, $subject2, $msg, $headers) && mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
?>
And JS
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "../contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Put your ajax call inside the validation process and use submitHandler.
This answer by #Sparky might save your day https://stackoverflow.com/a/15625824/6952155
Please refer to this and edit to suit in your code.
$(document).ready(function () {
$("#contactform").validate({
ignore: ":hidden",
rules: {
name: {
required: true,
minlength: 3
},
cognome: {
required: true,
minlength: 3
},
subject: {
required: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "formfiles/submit.php",
data: $(form).serialize(),
success: function () {
$(form).html("<div id='message'></div>");
$('#message').html("<h2>Your request is on the way!</h2>")
.append("<p>someone</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/ok.png' />");
});
}
});
return false; // required to block normal submit since you used ajax
}
});
});
Ondrej here, author of the tutorial on Bootstrapious.
I have just found out that there was an error in Bootstrap validator and it was not working correctly in combination with the Bootstrap modal.
The solution is downloading the latest version from https://github.com/1000hz/bootstrap-validator, currently 0.11.5.
Best,
Ondrej

Categories