Reputation: 53
Silly that I can't find this so I apologize in advance if I have duplicated, but I have looked through search engines and SO without finding what I need.
What is the proper way to submit an HTML form upon user click but only after I have asynchronously loaded data from a 3rd party API to fill in for some of the form's hidden fields?
I tried this structure, which has not worked:
form onclick = function1()
function1() calls function apicall that retrieves info from 3rd party api and in its completion handler then calls function2
function2 checks all form fields and returns true if form should be submitted, false if it should not
With this structure, my form is always submitted, although both the 3rd party api function completion handler and function2 are working properly on their own. function2 can return false all day long but the form still submits. What can I do about this? The asychronous timing seems alright but somehow the return false is not getting back to the FORM element.
Thank you for any tips or code samples.
Upvotes: 0
Views: 910
Reputation: 781098
Asynchronous functions can't return anything -- the caller isn't waiting for them to finish. So the form's onsubmit
handler should return false
to prevent the form from submitting.
Then in function2()
, if the form validation succeeds, it can call
document.getElementById('formID').submit();
to perform the actual form submission.
Upvotes: 3