0

I have a Vue.js form with a submit button. When clicked, a POST axios request is sent and a visual alert is triggered if the call is valid.

All is working fine but for a tiny little detail. The POST request does not get sent until AFTER the user clicks "OK" from the alert popup. This is not the intended behaviour. The request should be sent for as long as it is a valid call, and the popup is merely a visual confirmation.

Do you have any idea as to why the alert triggers the request? Thanks!

submitForm(formName) {
  this.$refs[formName].validate(valid => {
    if (valid) {
      axios.post(
        "https://dummy.com",
        { name: this.ruleForm },
        {
          headers: {
            "Content-type": "application/json"
          }
        }
      );
      alert(
        "Success!"
      );
    } else {
      alert("Error at submit. Check required fields.");
      console.log("Error at submit. Check required fields.");
      return false;
    }
  });
},

Bonus question: do you know a simple way to trigger a redirect after the user confirmed the alert? :D

Alex
  • 45
  • 2
  • 6
  • [https://stackoverflow.com/questions/33203157/prevent-alert-from-halting-the-execution-of-javascript](https://stackoverflow.com/questions/33203157/prevent-alert-from-halting-the-execution-of-javascript) – Frankenscarf Mar 01 '20 at 19:45

2 Answers2

0

The axios.post is async. You probably should call the success alert when the result returns:

 axios.post(
    "https://dummy.com",
    { name: this.ruleForm },
    {
      headers: {
        "Content-type": "application/json"
      }
    }
  ).then(res => {
     alert(
      "Success!"
     );
  }).catch(err => console.error(err)) // handle error here

Also, the alert blocks further execution until the user clicks ok (it's synchronous).

user3791775
  • 426
  • 3
  • 5
0
submitForm(formName) {
  this.$refs[formName].validate(valid => {
    if (valid) {
      axios.post(
        "https://dummy.com",
        { name: this.ruleForm },
        {
          headers: {
            "Content-type": "application/json"
          }
        }
      ).then(function(res){
          alert(
               "Success!"
                       );
              //write your code - response code is 200
    }).catch(function(err){
               alert(
                  "Error!"
                      );
               //write your code - response code != 200
     });

    } else {
      alert("Error at submit. Check required fields.");
      console.log("Error at submit. Check required fields.");
      return false;
    }
  });
},
Hossein Shafiei
  • 111
  • 1
  • 3