Is there a simple, other solution to trigger my boostrap toast which doesn't involve a button?
Maybe like :
button onclick ="trigger my bootstrap toast the easy way"
without the need of fetch or a button type="button"?
I think I have overlooked a simple way to implement it.
My site code looks like this currently:
<form>
<button=type"submit" name="need the name for my json key" value="need you also for my json"
This submits to my PHP background app, to save my value to JSON strings in a file.
Is there any simpler way to implement the call to trigger bootstrap toast?
The PHP background side is not the problem, for that I just want to POST my values to my PHP.
It sounds like you want to submit your form data asynchronously using JavaScript and then show a toast message when the async request is complete.
Toast messages can be triggered via JavaScript, as per the bootstrap documentation - there is no direct dependency on, or requirement to use, a button.
This code will listen for a form submit event, prevent the default postback behaviour, then send an async POST request via fetch()
which submits the form data to the server, and finally show the toast message when the POST request completes:
HTML:
<form id="frm1">
Enter your data: <input type="text" name="field1" />
<button type="submit" class="btn btn-primary">Submit form</button>
</form>
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<img src="..." class="rounded me-2" alt="...">
<strong class="me-auto">Bootstrap</strong>
<small>Test</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
Form submitted
</div>
</div>
</div>
JavaScript:
document.addEventListener("DOMContentLoaded", function() {
const frm = document.getElementById("frm1");
const toastLiveExample = document.getElementById("liveToast");
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);
frm.addEventListener("submit", function(event) {
event.preventDefault();
fetch(
"https://www.example.com/submit.php",
{
method: "POST",
body: new FormData(frm)
}
)
.then(function(response) {
return response.text();
})
.then(function(data) {
toastBootstrap.show();
})
.catch(function(err) {
console.log(`Error: ${err}`);
});
});
});
Live demo (with fake sink for the async request): https://jsfiddle.net/utazbhp2/3/