Not halting submit on API call error
Not halting submit on API call error
Workflow Automation Expert
Posts: 14Questions: 4Answers: 0
I would like to halt the form submission, if booking reference given has already been entered. The API call is being made to validate the data, and error returned - resulting in the error message is being displayed. However, the form data still continues to be submitted, creating the record.
bookingsEditor.on('preSubmit', function (e, o, action) {
if (action !== 'remove') {
let bookRef = this.field('booking.reference')
if (!bookRef.isMultiValue()) {
if (!bookRef.val()) {
bookRef.error('A booking reference must be entered.');
} else {
$.get("_/api/validate/booking?ref=" + bookRef.val())
.done(function(msg) {
// Booking reference not already used
}).fail(function(msg) {
bookRef.error('This booking reference has been used already.');
return false;
})
}
}
if (this.inError()) {
error_found = true;
return false;
}
}
});
Answers
Your
return false;
is being done inside thefail
function, not thepreSubmit
event handler. The upshot is that thepreSubmit
event handler returnsundefined
and thus is allowed to pass. TheinError()
check doesn't work as the Ajax is async, so the check happens before the error message has been set!What you have to do here is return a
Promise
.Allan
Thanks Allan,
Not really an expert on Promises, but was getting an Uncaught (in promise) Error as the above code you advised was not handling the rejection. Altered the code as follow to get it working.
Ah! Thanks for the correct and apologies. Its been a wee while since I've done that one myself
Allan