I have this simple form:
<form action="www.faildomain.com">
<input name="foo" value="bar">
<button type="submit">Submit</button>
</form>
In my case, the action will fail. But could it be that this is a valid action, but the user has experienced a connection error?
Are there different Javascript events generated or os this out of my control?
To capture response of form. submit with JavaScript, we can listen for the form's submit event. to add a form with some fields. And we call addEventListener on it with 'submit' and the form submit event callback to submit the form when the submit button is clicked.
Use the return value of the function to stop the execution of a form in JavaScript.
The submit event fires when the user clicks a submit button ( <button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form. submit() method directly.
This is out of your control if you don't handle the submit event. Basically, when you click on the submit button, your browser will do an HTTP POST request to your "action" URL.
If you want to check your inputs validity before sending it, what you'll have to do is to handle the form submission event: submit.
const myForm = document.getElementById('my-form');
// Add a listener to the submit event
myForm.addEventListener('submit', function (e) {
const errors = [];
// Check inputs...
if(errors.length) {
e.preventDefault(); // The browser will not make the HTTP POST request
return;
}
});
But, even with this code, you'll never know if the user has a network problem.
The only way you can check that kind of errors is by doing an asynchronous call to your backend route using Ajax (it's just an HTTP POST request, called asynchronously). For example, using jQuery:
$("#myForm").on("submit", function(e) {
event.preventDefault();
const data = {};
// Get data from form...
// Stop form from submitting normally
$.post("www.faildomain.com", data)
.done(function(data) {
// No problem
},
.fail(function (jqXHR, textStatus) {
// An error occured (the server responded with an error status, network issue, ...)
// More information about the error can be found in jqXHR and textStatus
},
.always(function () {
// This method is always executed whether there were an error or not
});
If you Submit it using Ajax you can get it via response headers. Take a look at this plugin:
http://malsup.com/jquery/form/#ajaxForm
it will help you a lot because it already have a method error for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With