Len
Len

Reputation: 21

Control the form submission based on the API response

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

Answers (2)

Heiko Thei&#223;en
Heiko Thei&#223;en

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:

  • The button first displays "Validate". When it is pressed at this stage, the 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".
  • If the button is pressed while displaying "Submit", the 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

Joshua Ooi
Joshua Ooi

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

Related Questions