Reputation: 183
I'm trying to work out how to prevent my form from redirecting upon submission. I have it to where it successfully sends emails, but it redirects to /cvg2/contact-submit.php upon submission. I don't want it to do that. I want it to inject the success/failure message into the "messages" div that is found at the bottom of the form.
Any help?
index.php
<form id="contact-form" method="post" action="/cvg2/contact-submit.php" role="form">
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input name="name" id="name" placeholder="Name" data-validation="alphanumeric" required="required"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input name="practice" id="practice" placeholder="Practice name"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input name="city-state" id="city-state" placeholder="City, State" required="required" data-validation="alphanumeric"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="styled-select">
<select name="position-select">
<option value="administrative">Administrative</option>
<option value="physician-shareholder">Physician Shareholder</option>
<option value="other">Other</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-12 two-up">
<input name="phone" id="phone" placeholder="(555)555-5555" required="required" data-validation="custom" data-validation-regexp="^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$" data-validation-error-msg="Invalid Phone Number"></input>
</div>
<div class="col-md-6 col-xs-12 col-sm-12 two-up">
<input name="email" id="email" placeholder="Email" data-validation="email" required="required"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input type="submit" value="SUBMIT" id="submit">
</div>
</div>
<div class="messages"></div>
</form>
contact-submit.php
<?php
// an email address that will be in the From field of the email.
$from = '[email protected]';
// an email address that will receive the email with the output of the form
$sendTo = '[email protected]';
// subject of the email
$subject = 'New Message Received';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'city-state' => 'Location', 'practice' => 'Practice', 'position-select' => 'Position');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted!';
// 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(0);
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'];
}
?>
scripts.js
//Form validation
$.validate({
validateOnBlur : true,
showHelpOnFocus : false
});
// when the form is submitted
$.on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "../cvg2/contact-submit.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
// data = JSON object that contact-submit.php returns
data: $(this).serialize(),
success: function (data)
{
// receive the type of the message: success x danger and apply it
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// Alert box html
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">' + messageText + '</div>';
// If 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;
}
});
Upvotes: 0
Views: 994
Reputation: 492
Make your life easy my friend:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<form id="contact-form" method="post" role="form">
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input name="name" id="name" placeholder="Name" data-validation="alphanumeric" required="required"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input name="practice" id="practice" placeholder="Practice name"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input name="city-state" id="city-state" placeholder="City, State" required="required" data-validation="alphanumeric"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="styled-select">
<select name="position-select">
<option value="administrative">Administrative</option>
<option value="physician-shareholder">Physician Shareholder</option>
<option value="other">Other</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-12 two-up">
<input name="phone" id="phone" placeholder="(555)555-5555" required="required" data-validation="custom" data-validation-regexp="^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$" data-validation-error-msg="Invalid Phone Number"></input>
</div>
<div class="col-md-6 col-xs-12 col-sm-12 two-up">
<input name="email" id="email" placeholder="Email" data-validation="email" required="required"></input>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<input type="submit" value="SUBMIT" id="submit">
</div>
</div>
<div id="error_messages"></div>
</form>
<script type="text/javascript">
$.validate({
validateOnBlur : true,
showHelpOnFocus : false
});
$("#contact-form").submit(function(e) {
$.ajax({
type: "POST",
url: "../cvg2/contact-submit.php",
data: $("#contact-form").serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">' + messageText + '</div>';
if (messageAlert && messageText) {
$('#error_messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
e.preventDefault();
});
</script>
</body>
</html>
contact-submit.php:
<?php
$sendTo = '[email protected]';
// subject of the email
$subject = 'New Message Received';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'city-state' => 'Location', 'practice' => 'Practice', 'position-select' => 'Position');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted!';
// 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(0);
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'];
}
?>
Upvotes: 1
Reputation: 3308
When learning HTML, we learn to use <form>
tags - as the first way - to save form fields to the database. They aren't required when upgrading the website to use AJAX. They can be removed.
The page is unloading upon submission, because the <form>
tag is still running it's method=POST
operation. The <form>
tag is still trying to redirect to the page, which is in this attribute: action="/cvg2/contact-submit.php"
.
You can safely delete these HTML tags, as they are only useful for form POST-BACKS, which are the opposite of AJAX calls:
<form id="contact-form" method="post" action="/cvg2/contact-submit.php" role="form">
</form>
Then you can change this tag from <input type="submit" value="SUBMIT" id="submit">
to <button id="submit">Submit</button>
and it will still use jQuery's AJAX call to send the email.
Use it with this:
$("#submit").on('click', function() {...});
If you really want to use the <form>
tag, then you can give it an attribute like this: onSubmit="return false;"
, where it will look like this:
<form id="contact-form" method="post" action="/cvg2/contact-submit.php" role="form" onSubmit="return false;">
...
</form>
For reference see:
Upvotes: 1
Reputation: 57
Why are you setting up an "action" tag to your form if you don't wan't any redirection ?
Maybe would you like to set up an AJAX request to execute when the $('#submit') element is clicked ?
Or maybe just put the code in "contact-submit.php" just on the top of your index.php, so that it still works without redirection ?
Your code is just working perfectly for what you wrote... "Action tag" for the form element in HTML is used to redirect so... Don't use it here ;)
Upvotes: 0