Topic: Static contact form and toast
pawled free asked 3 years ago
How to add toast notifications (success and danger) to static contact form (Formspree)? Vanilla JS. I have seen a lot of jQuery static form examples, unfortunately.
Currently I use this script. It adds text notifications to the div.
var form = document.getElementById("contactForm");
var formMessage = document.getElementById("formMessage");
form.onsubmit = function(event) {
event.preventDefault();
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", form.action, true);
xhr.onload = function(e) {
console.log(xhr);
var response = JSON.parse(xhr.response);
if (xhr.status === 200) {
formMessage.innerHTML = "Sent!";
} else {
formMessage.innerHTML = "Error: " + response.error;
}
};
xhr.send(formData);
};
Grzegorz Bujański staff answered 3 years ago
Try this:
xhr.onload = function(e) {
var response = JSON.parse(xhr.response);
if (xhr.status === 200) {
document.querySelector('.toast-body').innerHTML = "Sent!";
form.reset();
} else {
document.querySelector('.toast-body').innerHTML = "Error: " + response.error;
}
let instance = mdb.Toast.getInstance(document.getElementById('basic-success-example'));
instance.show();
};
Grzegorz Bujański staff answered 3 years ago
Unfortunately we have no experience with Formspree. The way you choose is fine and should work fine. The only thing I would change would be to add two toasts on the page - success, and danger. The first one would appear after correctly submitting the form, danger if something goes wrong.
To show the right toast use the show
method. Below is an example of launching a success toast:
HTML code:
<div
class="toast fade mx-auto"
id="basic-success-example"
role="alert"
aria-live="assertive"
aria-atomic="true"
data-mdb-autohide="true"
data-mdb-delay="2000"
data-mdb-position="top-right"
data-mdb-append-to-body="true"
data-mdb-stacking="true"
data-mdb-width="350px"
data-mdb-color="success"
>
<div class="toast-header text-white">
<strong class="me-auto">MDBootstrap</strong>
<small>11 mins ago</small>
<button type="button" class="btn-close btn-close-white" data-mdb-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body text-white">Success Basic Example</div>
</div>
JS code:
let instance = mdb.Toast.getInstance(document.getElementById('basic-success-example'));
instance.show();
pawled free commented 3 years ago
Can you put this part of code into my own script?
How to clear the form after successful submission?
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Free
- Premium support: No
- Technology: MDB Standard
- MDB Version: 3.2.0
- Device: Any
- Browser: Any
- OS: Any
- Provided sample code: No
- Provided link: No