Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  62] [ 2]  / answers: 1 / hits: 17116  / 9 Years ago, mon, may 11, 2015, 12:00:00

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?


More From » forms

 Answers
31

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
});

[#66645] Friday, May 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranav

Total Points: 693
Total Questions: 119
Total Answers: 119

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
pranav questions
Thu, Feb 10, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Mon, Sep 6, 21, 00:00, 3 Years ago
Mon, Mar 8, 21, 00:00, 3 Years ago
;