I'm building a website using Bootstrap and needed a contact form, so I decided to use the one from Bootstrapious. The form works properly and I can receive the messages by email, but the success message appears on a blank page instead of the form page.
I've seen two questions posted here that referred to a similar problem:
PHP contact form redirects to contact.php with success message - This person resolved the problem himself but doesn't really explain how.
PHP contact form not landing on right page - This one had his problem resolved by someone else, but it doesn't seem to work for me (or maybe I just don't understand the solution given).
Here is my page if you want to try it to see exactly what it does.
And here is the code (I tried to cut the irrelevant parts, but since I don't really know where the problem is, I might have left a little too much).
HTML page:
<!doctype html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap core CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"></head>
<body>
<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">Prénom*</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Prénom" required="required" data-error="Votre prénom est requis.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Nom de famille*</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Nom de famille" required="required" data-error="Votre nom de famille est requis.">
<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">Courriel*</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Courriel" required="required" data-error="Votre adresse courriel est requise.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Téléphone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Numéro de téléphone">
<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_postal">Code postal*</label>
<input id="form_postal" type="text" name="codepostal" class="form-control" placeholder="Code postal" required="required" data-error="Votre code postal est requis." pattern="[A-Za-z][0-9][A-Za-z]\s?[0-9][A-Za-z][0-9]">
<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" placeholder="Votre message" rows="4" required="required" data-error="Veuillez entrer votre message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Envoyer">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> Champs obligatoires</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.container -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../../../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
<script src="../../../../assets/js/vendor/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="validator.js"></script>
<script src="contact.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.css"></script>
Contact.php:
<?php
$from = 'test <[email protected]>';
$sendTo = 'test <[email protected]>';
$subject = 'Nouveau message';
$fields = array('name' => 'Prénom', 'surname' => 'Nom de famille', 'phone' => 'Téléphone', 'email' => 'Courriel', 'message' => 'Message');
$okMessage = 'Le formulaire de contact a bien été envoyé. Merci! Nous vous contacterons dans les plus brefs délais.';
$errorMessage = 'Une erreur s\'est produite en envoyant le formulaire. Veuillez réessayer plus tard.';
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Le formulaire est vide');
$emailText = "Vous avez un nouveau message de votre formulaire de contact\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'];
}
Contact.js:
$(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);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Edit 06/03: I've tried Nitin Sharma's suggestion, but it doesn't work. I can redirect to the first page, but then, the success message doesn't appear at all.