Skip to content

Commit c6e3e89

Browse files
author
raspgot
committed
Remove Jquery dependencies
1 parent ab29d39 commit c6e3e89

File tree

4 files changed

+92
-119
lines changed

4 files changed

+92
-119
lines changed

AjaxForm.js

Lines changed: 61 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,73 @@
11
/**
2-
* .validate (https://jqueryvalidation.org)
3-
* .post (https://api.jquery.com/jQuery.post/)
4-
* reCaptcha v3 (https://developers.google.com/recaptcha/docs/v3)
2+
* .checkValidity | https://getbootstrap.com/docs/5.3/forms/validation
3+
* FormData | https://developer.mozilla.org/en-US/docs/Web/API/FormData
4+
* fetch | https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
5+
* reCaptcha v3 | https://developers.google.com/recaptcha/docs/v3
6+
*
57
* @author Raspgot
68
*/
79

8-
const publicKey = ''; // GOOGLE public key
10+
const publicKey = 'GOOGLE_PUBLIC_KEY'; // GOOGLE public key
911

10-
$(function () {
11-
check_grecaptcha();
12+
onload = () => {
13+
'use strict'
1214

13-
// If you add field, add rule and error message in validate function
14-
$('#contactform').validate({
15-
// Form fields rules
16-
rules: {
17-
name: {
18-
required: true,
19-
minlength: 3,
20-
},
21-
email: {
22-
required: true,
23-
email: true,
24-
},
25-
message: {
26-
required: true,
27-
minlength: 5,
28-
},
29-
},
30-
// Error messages
31-
messages: {
32-
name: {
33-
required: 'Please enter your name.',
34-
minlength: 'Must be at least 3 characters long.',
35-
},
36-
email: 'Please enter a valid email.',
37-
message: {
38-
required: 'Please enter your message.',
39-
minlength: 'Must be at least 5 characters long.',
40-
},
41-
},
42-
errorClass: 'invalid-feedback',
43-
// Dynamic validation classes
44-
highlight: function (element) {
45-
// Invalid
46-
$(element).addClass('is-invalid').removeClass('is-valid');
47-
},
48-
unhighlight: function (element) {
49-
// Valid
50-
$(element).addClass('is-valid').removeClass('is-invalid');
51-
},
52-
// Action on submit
53-
submitHandler: function (form, event) {
54-
event.preventDefault();
55-
$('#sendtext').text('SENDING...');
56-
$.post(form.action, $(form).serialize())
57-
.done(function (response) {
58-
alertShowing(JSON.parse(response));
59-
$('#sendtext').text('SEND');
60-
$('#submit-btn').prop('disabled', true);
61-
check_grecaptcha();
62-
})
63-
.fail(function (response) {
64-
alert(response);
65-
})
66-
.always(function () {
67-
// Timeout to reset form
15+
checkRecaptcha();
16+
17+
let forms = document.querySelectorAll('.needs-validation');
18+
let spinner = document.getElementById('loading-spinner');
19+
20+
Array.prototype.filter.call(forms, function (form) {
21+
form.addEventListener('submit', function (event) {
22+
if (form.checkValidity() === false) {
23+
event.preventDefault();
24+
event.stopPropagation();
25+
}
26+
form.classList.add('was-validated');
27+
if (form.checkValidity() === true) {
28+
event.preventDefault();
29+
form.classList.remove('was-validated');
30+
spinner.classList.remove('d-none');
31+
32+
let data = new FormData(form);
33+
let alertClass = 'alert-danger';
34+
35+
fetch('AjaxForm.php', {
36+
method: 'post',
37+
body: data
38+
}).then((data) => {
39+
return data.text();
40+
}).then((txt) => {
41+
txt = JSON.parse(txt);
42+
if (txt.error === false) {
43+
alertClass = 'alert-success';
44+
}
45+
let alertBox = '<div class="alert ' + alertClass + '">' + txt.message + '</div>';
46+
if (alertClass && txt) {
47+
form.querySelector('#alert-statut').insertAdjacentHTML('beforeend', alertBox);
48+
form.reset();
49+
checkRecaptcha();
50+
}
51+
spinner.classList.add('d-none');
6852
setTimeout(function () {
69-
$('#submit-btn').prop('disabled', false);
70-
$('form').trigger('reset');
71-
$('form').each(function () {
72-
$(this)
73-
.find('.form-control')
74-
.removeClass('is-valid');
75-
});
76-
}, 3000);
53+
form.querySelector('#alert-statut').innerHTML = '';
54+
}, 5000);
55+
}).catch((err) => {
56+
console.log('Error encountered: ' + err);
57+
spinner.classList.add('d-none');
7758
});
78-
},
59+
}
60+
}, false);
7961
});
80-
});
62+
};
8163

82-
// Get token from API
83-
function check_grecaptcha() {
64+
var checkRecaptcha = () => {
8465
grecaptcha.ready(function () {
85-
grecaptcha
86-
.execute(publicKey, {
87-
action: 'ajaxForm',
88-
})
89-
.then(function (token) {
90-
$("[name='recaptcha-token']").val(token);
91-
});
66+
grecaptcha.execute(publicKey, {
67+
action: 'submit'
68+
}).then(function (token) {
69+
// input with recaptcha-token name take the recaptcha token value
70+
document.getElementsByName('recaptcha-token')[0].value = token;
71+
});
9272
});
93-
}
94-
95-
// Show response in .alert
96-
function alertShowing(response) {
97-
// Apply class alert
98-
if (response.error == true) {
99-
$('#response-alert').addClass('alert-danger');
100-
$('#response-alert').removeClass('alert-success');
101-
} else {
102-
$('#response-alert').addClass('alert-success');
103-
$('#response-alert').removeClass('alert-danger');
104-
}
105-
// Display alert with message
106-
$('#response-alert').html(response.message);
107-
$('#response-alert').removeClass('d-none');
108-
$('#response-alert').addClass('d-block');
109-
}
73+
};

AjaxForm.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
$email = filter_var(secure($_POST['email']), FILTER_SANITIZE_EMAIL) ?? statusHandler(true, HANDLER_MSG['enter_email']);
6161
$message = secure($_POST['message']) ?? statusHandler(true, HANDLER_MSG['enter_message']);
6262
$token = secure($_POST['recaptcha-token']) ?? statusHandler(true, HANDLER_MSG['token-error']);
63-
$ip = filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP) ?? filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
63+
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'];
6464
$date = new DateTime();
6565
}
6666

@@ -71,15 +71,15 @@
7171
'date' => $date->format('j/m/Y H:i:s'),
7272
'name' => $name,
7373
'email' => $email,
74-
'ip' => $ip,
74+
'ip' => filter_var($ip, FILTER_VALIDATE_IP),
7575
'message' => $message
7676
]);
7777

7878
# Verifying the user's response
7979
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY);
8080
$resp = $recaptcha
8181
->setExpectedHostname($_SERVER['SERVER_NAME'])
82-
->verify($token, $ip);
82+
->verify($token, filter_var($ip, FILTER_VALIDATE_IP));
8383

8484
if ($resp->isSuccess()) {
8585
# Instanciation of PHPMailer

README.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
# Contact-Form-PHP
22

3-
![version](https://img.shields.io/badge/version-1.2.0-blue.svg) ![code size](https://img.shields.io/github/languages/code-size/raspgot/Contact-Form-PHP) [![closed issues](https://img.shields.io/github/issues-closed-raw/raspgot/Contact-Form-PHP)](https://github.com/raspgot/Contact-Form-PHP/issues?q=is%3Aissue+is%3Aclosed)
3+
![version](https://img.shields.io/badge/version-1.3.0-blue.svg) ![code size](https://img.shields.io/github/languages/code-size/raspgot/Contact-Form-PHP) [![closed issues](https://img.shields.io/github/issues-closed-raw/raspgot/Contact-Form-PHP)](https://github.com/raspgot/Contact-Form-PHP/issues?q=is%3Aissue+is%3Aclosed)
44
[![stars](https://img.shields.io/github/stars/raspgot/Contact-Form-PHP?style=social)](https://github.com/raspgot/Contact-Form-PHP/stargazers)
55

66
Basic, simple and secure bootstrap contact form.
7+
Jquery FREE.
78
Using Ajax protocol, PHP & JS validations inputs, SMTP mail sending, rejected not found domain and Google reCAPTCHA v3.
89

910
![](https://dev.raspgot.fr/github/contact-form-php/gif_github_1.2.0.gif)
@@ -13,7 +14,7 @@ You can try this form here: https://dev.raspgot.fr/github/contact-form-php
1314

1415
## Features
1516
* PHP 8.2.3 ✔️ [(See supported versions)](https://www.php.net/supported-versions.php)
16-
* Bootstrap 4.X/5.X
17+
* Bootstrap 5.X
1718
* Ajax submission
1819
* Google reCAPTCHA v3
1920
* PHPMailer SMTP Authentication
@@ -48,13 +49,18 @@ const SECRET_KEY = ''; # GOOGLE secret key
4849

4950
**AjaxForm.js**
5051
```javascript
51-
const publicKey = ''; // GOOGLE public key
52+
const publicKey = 'GOOGLE_PUBLIC_KEY';
5253
```
5354

5455
**index.html**
5556
```html
5657
<script src="https://www.google.com/recaptcha/api.js?render=GOOGLE_PUBLIC_KEY"></script>
5758
```
59+
You can cuztomise text error:
60+
```html
61+
<div class="valid-feedback">Name looks good</div>
62+
<div class="invalid-feedback">Please provide a valid name</div>
63+
```
5864

5965
YOU MUST ALLOW `allow_url_fopen` DIRECTIVE ON YOUR SERVER IN `php.ini`
6066

@@ -66,6 +72,4 @@ You can visit my [Portfolio](https://raspgot.fr) and star this repo if you like
6672
## Dependencies
6773
* [PHPMailer](https://github.com/PHPMailer/PHPMailer)
6874
* [reCAPTCHA PHP client library](https://github.com/google/recaptcha)
69-
* [Bootstrap](https://github.com/twbs/bootstrap)
70-
* [Jquery](https://github.com/jquery/jquery)
71-
* [jquery-validation](https://github.com/jquery-validation/jquery-validation)
75+
* [Bootstrap](https://github.com/twbs/bootstrap)

index.html

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,36 @@ <h1>Contact-Form-PHP</h1>
1515
<a class="github-button" href="https://github.com/raspgot/Contact-Form-PHP" data-icon="octicon-star" data-size="large" data-show-count="true" aria-label="Star raspgot/Contact-Form-PHP on GitHub">Give a star !</a>
1616
</div>
1717

18-
<!-- Alert status -->
19-
<div id="response-alert" class="alert d-none" role="alert"></div>
20-
2118
<!-- Form -->
2219
<div class="shadow rounded p-5">
23-
<form action="AjaxForm.php" method="post" class="needs-validation" id="contactform" novalidate>
24-
<!-- Input -->
20+
<form action="AjaxForm.php" method="post" class="needs-validation" novalidate>
21+
<!-- Alert status -->
22+
<div id="alert-statut"></div>
23+
24+
<!-- Inputs -->
2525
<div class="mb-3">
2626
<label for="name" class="form-label">Name</label>
27-
<input type="text" class="form-control" id="name" name="name" required>
27+
<input type="text" class="form-control" name="name" required>
28+
<div class="valid-feedback">Name looks good</div>
29+
<div class="invalid-feedback">Please provide a valid name</div>
2830
</div>
2931
<div class="mb-3">
3032
<label for="email" class="form-label">Email</label>
31-
<input type="email" class="form-control" id="email" name="email" required>
33+
<input type="email" class="form-control" name="email" required>
34+
<div class="valid-feedback">Email looks good</div>
35+
<div class="invalid-feedback">Please provide a valid email</div>
3236
</div>
3337
<div class="mb-4">
3438
<label for="message" class="form-label">Message</label>
35-
<textarea class="form-control" id="message" name="message" rows="4" required></textarea>
39+
<textarea class="form-control" name="message" rows="4" required></textarea>
40+
<div class="valid-feedback">The message looks good</div>
41+
<div class="invalid-feedback">Please provide a valid message</div>
3642
</div>
3743

3844
<!-- Submit button -->
39-
<button type="submit" class="btn btn-primary w-100" id="submit-btn">
40-
<span id="sendtext">SEND</span>
45+
<button type="submit" class="btn btn-primary w-100">
46+
<span class="spinner-border spinner-border-sm me-2 d-none" id="loading-spinner" role="status" aria-hidden="true"></span>
47+
<span>SEND</span>
4148
</button>
4249

4350
<!-- IMPORTANT | Token value recaptcha -->
@@ -47,9 +54,7 @@ <h1>Contact-Form-PHP</h1>
4754
</main>
4855

4956
<script defer src="https://www.google.com/recaptcha/api.js?render=GOOGLE_PUBLIC_KEY"></script>
50-
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
51-
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
52-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
57+
<script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
5358
<script src="AjaxForm.js"></script>
5459
<!-- Github widget (you can delete for your own utilisation) -->
5560
<script defer src="https://buttons.github.io/buttons.js"></script>

0 commit comments

Comments
 (0)