0

I have a simple login form with a button that has a reactive text {{ msg }} by default it says log in and when the user sends the form it changes to logging.... If the form fails then I want to say send again.

I'm using sweetalert for the warnings and I intend to change the msg data inside the sweetAlert. However for some reason it returns a undefined to this.msg

html

<form id="login_form">
 <input class="form-control" type="text" required="" name="email" placeholder="Email">
 <input class="form-control" type="password" required="" name="password" placeholder="Password">
 <button class="btn" type="submit">Log In</button>
</form>

Javascript

export default {
 data() {
   return {
     msg: "Log in"
    }
  },
methods: {
submitForm() {
  const loginData = $("#login_form").serializeArray();
  const v = this;
  this.msg = "logging..."
  $.ajax({
    url: "/authentication",
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    data: JSON.stringify({
      strategy: "local",
      email: loginData[0].value,
      password: loginData[1].value
    }),
    success: function (data) {
      window.location.replace("/");
       this.msg = "logged!"
    },
    error: function (error) {
      if (error.status === 401) {
        swal("Wrong email or password");
        this.msg = "Try again?";
        console.log("this.msg) //returns undefined
      } else if (error.status === 400) {
        swal("Wrong email or password");
        this.msg = "Try again?";
      } else {
        swal("Error. Try again!");
        this.msg = "Try again?";
      }
    }
  });
}
}

I also tried promises but it also returns this.msg as undefined.

if I console.log(this.msg) inside the sweetAlert it returns undefined.

Phil
  • 157,677
  • 23
  • 242
  • 245
ahzep
  • 180
  • 3
  • 15

1 Answers1

1

I doubt its the context behavior. Try this one

export default {
 data() {
   return {
     msg: "Log in"
    }
  },
methods: {
submitForm() {
  const self = this;
  const loginData = $("#login_form").serializeArray();
  const v = this;

  self.msg = "logging..."
  $.ajax({
    url: "/authentication",
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    data: JSON.stringify({
      strategy: "local",
      email: loginData[0].value,
      password: loginData[1].value
    }),
    success: function (data) {
      window.location.replace("/");
       self.msg = "logged!"
    },
    error: function (error) {
      if (error.status === 401) {
        swal("Wrong email or password");
        self.msg = "Try again?";
        console.log(self.msg) //returns undefined
      } else if (error.status === 400) {
        swal("Wrong email or password");
        self.msg = "Try again?";
      } else {
        swal("Error. Try again!");
        self.msg = "Try again?";
      }
    }
  });
}
}
ßiansor Å. Ålmerol
  • 2,849
  • 3
  • 22
  • 24