Is it possible to detect form submit fail in javascript? -
i have simple form:
<form action="www.faildomain.com"> <input name="foo" value="bar"> <button type="submit">submit</button> </form> in case, action fail. valid action, user has experienced connection error?
are there different javascript events generated or os out of control?
this out of control if don't handle submit event. basically, when click on submit button, browser http post request "action" url.
if want check inputs validity before sending it, you'll have handle form submission event: submit.
var myform = document.getelementbyid('my-form'); // add listener submit event myform.addeventlistener('submit', function (e) { var errors = []; // check inputs... if(errors.length) { e.preventdefault(); // browser not make http post request return; } }); but, code, you'll never know if user has network problem.
the way can check kind of errors doing asynchronous call backend route using ajax (it's http post request, called asynchronously). example, using jquery:
$("#myform").on("submit", function(e) { event.preventdefault(); var data = {}; // data form... // stop form submitting $.post("www.faildomain.com", data) .done(function(data) { // no problem }, .fail(function (jqxhr, textstatus) { // error occured (the server responded error status, network issue, ...) // more information error can found in jqxhr , textstatus }, .always(function () { // method executed whether there error or not });
Comments
Post a Comment