• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Problems with contact form and recaptcha

Explorer ,
Sep 10, 2020 Sep 10, 2020

Copy link to clipboard

Copied

Hello everybody,

 

I seem to have gotten myself into a deep hole that I can't get out of...
I have followed a tutorial making a contact form with bootstrap and a recaptcha. I can't get it to work.
When I try it out, the form generates the success message from my contact.php file, but no mail arrives in my mailbox. And I never get to fill in any question from the recaptcha. The form I am intending to use, is at 1alarm.se/kontakt.html.

Code is here:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Välkommen till 1Alarm!</title>
<!-- Bootstrap -->
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> -->
<link href="css/bootstrap-4.4.1.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet" type="text/css">
<link href="css/main.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html"><img src="bilder/Logga_med_svart_text_vit_bakgrund.png" class="rounded img-fluid" alt="1Alarm Logo"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">STARTSIDA </a>
</li>
<li class="nav-item">
<a class="nav-link" href="hemlarm.html">HEMLARM</a>
</li>
<li class="nav-item">
<a class="nav-link" href="foretag.html">FÖRETAGSLARM</a></li>
<li class="nav-item">
<a class="nav-link" href="erbjudande.html">KAMPANJERBJUDANDE</a>
</li>
<li class="nav-item">
<a class="nav-link" href="jobba.html">JOBBA HOS OSS</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="kontakt.html">KONTAKT <span class="sr-only">(current)</span></a>
</li>

</ul>
</div>
</nav>
<div class="container mt-2">
<div class="row">
<div class="col-12">
<img src="bilder/kontakta_oss.jpg" class="img-fluid" alt="Kontakta oss">
<div class="container mt-2"></div></div>
<div class="row">

<div class="col-xl-8 offset-xl-2 py-5">

<h1>Kontakta oss</h1>

<p class="lead"></p>

<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">Förnamn *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Skriv in ditt förnamn, tack *" required="required" data-error="Namn krävs.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Efternamn *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Skriv ditt efternamn här *" required="required" data-error="Namn krävs.">
<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" placeholder="Skriv din mailadress här *" required="required" data-error="Giltig e-post krävs.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label for="form_phone">Telefon</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Telefonnummer">
<div class="help-block with-errors"></div>
</div>
</div>
<div>
<div class="col-md-12">
<div class="form-group">
<label for="form_need">Vad gäller ditt meddelande? *</label>
<select id="form_need" name="need" class="form-control" required="required" data-error="Krävs.">
<option value=""></option>
<option value="Request quotation">Mer information om hemlarm</option>
<option value="Request order status">Mer information om företagslarm</option>
<option value="Request copy of an invoice">Jag söker jobb</option>
<option value="Other">Jag vill komma i kontakt med kundtjänst</option>
</select>
<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">Meddelande *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Skriv ditt meddelande här *" rows="4" required="krävs" data-error="Skriv ett meddelande, tack."></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="Skicka meddelande">
</div>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeYUr8ZAAAAAB6cFkv1Gjs6dexbNSUmhlRb131G" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
<input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
<div class="help-block with-errors"></div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> Dessa fält måste fyllas i.</p>
</div>
</div>
</div>
</div>

</form>
</div>

</div>
</div>

<hr>
<div class="container">
<div class="row">
<div class="col-md-6"><h3 class="rubrik">Kontaktinformation</h3>
<address>
<strong>1 Alarm</strong><br>
Tel: 010-3330658<br>
Tel: 010-3330566<br>
Telefontid:<br>
Mån - Fre: kl: 10-12 och kl: 13-15
</address>
<address>
<br>
<a href="kontakt.php"><img src="bilder/knapp_mejla_kundtjanst.png" class="rounded img-fluid" alt="Mejla kundtjänst"></a><br>
&nbsp; &nbsp;
</address>
<address>
&nbsp;
</address></div>
<div class="col-md-6"> <h5 class="rubrik">&nbsp;</h5>
<p>&nbsp;</p>
<p><img src="bilder/samlingsloggor_SSF.jpg" class="rounded img-fluid" alt="Placeholder image"> </p></div>
</div>
</div>
</div>

<hr>
<footer class="text-center">
<div class="container">
<div class="row">
<div class="col-12">
<p>Copyright ©2020 1 Alarm Sverige AB. All rights reserved.</p>
<h6 align="center"><a href="gdpr.html">Integritetspolicy (GDPR)</a></h6>
</div>
</div>
</div>

</footer>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script src="validator.js"></script>
<script src="contact.js"></script>
</body>
</html>

 

Code for validator.js:

$(function () {

window.verifyRecaptchaCallback = function (response) {
$('input[data-recaptcha]').val(response).trigger('change')
}

window.expiredRecaptchaCallback = function () {
$('input[data-recaptcha]').val("").trigger('change')
}

$('#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">&times;</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});

 

Code for 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();


// 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">&times;</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;
}
})
});

 

Code for contact.php:

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');

// configure
// an email address that will be in the From field of the email.
$from = 'Kontaktformulär <info@1alarm.se';

// an email address that will receive the email with the output of the form
$sendTo = '<cdvdesign@gmail.com>';

// subject of the email
$subject = 'Ny kontakt från hemsidan';

// 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 = 'Ditt meddelande har skickats! Vi återkommer till dig inom kort.';

// If something goes wrong, we will display this message.
$errorMessage = 'Något gick fel och ditt meddelande har inte skickats. Försök igen senare.';

// ReCaptch Secret
$recaptchaSecret = '6LeYUr8ZAAAAAHN_E-2VwB39M9-thW0jI9MKn9wI';

// 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 (!empty($_POST)) {

// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block

if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}

// do not forget to enter your secret key from https://www.google.com/recaptcha/admin

$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());

// we validate the ReCaptcha field together with the user's IP address

$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}

// everything went well, we can compose the message, as usually

$emailText = "Ny kontakt från hemsidan\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' => $e->getMessage());
}

if ($responseArray['type'] == 'success') {
// success redirect

header('Location: http://www.1alarm.se/success.html');
}
else {
//error redirect
header('Location: http://www.1alarm.se/error.html');
}

 

I would be so grateful if the collective mindtrust here is able to help me!


Kind regards,
Carolin

TOPICS
Bootstrap , Code , Other

Views

770

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Explorer , Sep 11, 2020 Sep 11, 2020

Update again:

 

The ReCaptcha part now seems to be working, but email still doesn't get sent. 

Have checked and re-checked the code to the best of my ability (which isn't great), but can't find any errors.

 

UPDATE: I have now managed to work everything out, and everything is working!

Thank you.

 

Kind regards,

Carolin

Votes

Translate

Translate
Community Expert ,
Sep 10, 2020 Sep 10, 2020

Copy link to clipboard

Copied

Does your web server and hosting plan support PHP and the PHP mail () function?  If unsure, ask your hosting provider.

If not, the mail will never get sent from your server. 

 

Nancy O'Shea— Product User, Community Expert & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Sep 11, 2020 Sep 11, 2020

Copy link to clipboard

Copied

Thank you Nancy, I've doublechecked and they support both.

 

Kind regards Carolin

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Sep 11, 2020 Sep 11, 2020

Copy link to clipboard

Copied

Update: I re-did the tutorial, but this time without the reCaptcha, and then it worked. 

As I added the reCaptcha, things are not working anymore. 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Sep 11, 2020 Sep 11, 2020

Copy link to clipboard

Copied

Update again:

 

The ReCaptcha part now seems to be working, but email still doesn't get sent. 

Have checked and re-checked the code to the best of my ability (which isn't great), but can't find any errors.

 

UPDATE: I have now managed to work everything out, and everything is working!

Thank you.

 

Kind regards,

Carolin

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2020 Sep 11, 2020

Copy link to clipboard

Copied

LATEST

So what was the missing ingredient in your Captcha?

 

Nancy O'Shea— Product User, Community Expert & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines