Reputation: 21
I want to submit my form depending on the API response.
If the API response is valid, submit the form if not, don't submit and don't reload the page until the response is valid
<form accept-charset="UTF-8" class="myForm" id="myFormID" onsubmit="return getResult()">
<button id="if-submit" type="submit">Submit</button></div>
function getResult(){
function makeGetRequest(path) {
return new Promise(function (resolve, reject) {
axios.get(path).then(
(response) => {
var result = response.data;
resolve(result);
},
(error) => {
reject(error);
}
);
});
}
async function main() {
var emailAdd = (document.getElementById('inf_field_Email').value);
if (emailAdd != ""){
var result = await makeGetRequest(server+emailAdd);
let form = document.getElementById('myFormID');
if (result.status == 'valid'){
form.action = "https://nextpage.com";
return true;
}
else
{
return false;
}
}
else{
console.log('Please put email address')
}
}
main();
}
I have this code, however, it just reloading after I click the submit button
Upvotes: -1
Views: 46
Reputation: 17487
Your idea seems to be to prevent form submission by returning false
from the onsubmit
event. But you would have to return that synchronously, which means that you cannot let the return value depend on the result of a validating GET request, because this is inherently asynchronous.
You could implement a two-step submission like illustrated below:
onsubmit
function returns false
but asynchronously triggers a validation request (which in this example does not really validate anything, but what matters is that it introduces asynchronousness). Upon successful validation, the button text is changed to "Submit". Otherwise, validation errors would be displayed while the button stays on "Validate".onsubmit
function returns true
and the form is actually submitted.Note that users can circumvent the validation, therefore you cannot rely on the validation having succeeded when the form is submitted. You must instead repeat the validation as part of the "real" form-processing.
function validateOrSubmit(form) {
if (form.button.value === "Submit") return true;
fetch("https://httpbin.org/anything/" + form.code.value).then(function(r) {
if (r.status === 200) form.button.value = "Submit";
});
return false;
}
<form action="https://httpbin.org/post" method="post" onsubmit="return validateOrSubmit(this)">
Three letter code <input name="code"/>
<input type="submit" name="button" value="Validate" />
</form>
Upvotes: 0
Reputation: 1192
With <button type="submit">
the page will always load. Use event.preventDefault()
method to block the reload action and proceed with whenever action you wanted after that.
Upvotes: 0