You can do it but will have to be done programmatically and not implicitly through the action
attribute. For that, you can use then/catch
from Promises or try/catch with async/await
like the example below:
<form>
<input type="text" name="fname" />
<br />
<input type="text" name="lname" />
<br />
<button type="submit">Send</button>
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const elements = event.target;
const firstName = elements['fname'].value;
const lastName = elements['lname'].value;
const dataToSend = { firstName, lastName };
try {
const response = await fetch('/example', {
method: 'POST',
body: JSON.stringify(dataToSend),
headers: { 'Content-Type': 'application/json' },
});
const data = await response.json();
console.log('Data returned from the server', data);
} catch (error) {
console.log('Uups! Something went wrong', error);
}
});
</script>