Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting component data using AJAX #467

Closed
mikemartin opened this issue May 10, 2020 · 3 comments
Closed

Setting component data using AJAX #467

mikemartin opened this issue May 10, 2020 · 3 comments

Comments

@mikemartin
Copy link

I'm submitting a form with AJAX and having trouble setting my component's success value.

Here's what I have so far:

<div x-show="subscribeVisible" x-data="{ subscribeVisible: false, success: false }">
  <form id="subscribe" x-ref="form">
      <input type="email" name="email" />
    <button @click.prevent="submitForm($refs)">Subscribe</button>
  </form>
  <div x-show="success">Form submitted!</div>
</div>

<script>
  function submitForm($refs) {
    axios.post($refs.form.action, new FormData($refs.form))
    .then(response => {
      console.log(response.data);
      return this.success === true
    });
  }
</script>
@HugoDF
Copy link
Contributor

HugoDF commented May 10, 2020

You need to make your x-data a function call

<div x-show="subscribeVisible" x-data="component()">
  <form id="subscribe" x-ref="form">
      <input type="email" name="email" />
    <button @click.prevent="submitForm($refs)">Subscribe</button>
  </form>
  <div x-show="success">Form submitted!</div>
</div>

<script>
  function component () {
    return {
      subscribeVisiblefalse,
      successfalse,
      submitForm() {
        axios.post(this.$refs.form.action, new FormData(this.$refs.form))
        .then(response => {
          console.log(response.data);
          return this.success === true
        });
      }
    }
  }
</script>

@mikemartin
Copy link
Author

Thanks so much. That did it. Here's the final solution:


<script>
  function subscribe () {
    return {
      errors: [],
      subscribeVisible: false,
      success: false,
      submitForm() {
        axios.post(this.$refs.form.action, new FormData(this.$refs.form))
        .then(response => {
          if (response.data.success) {
            this.errors = [];
            this.success = true;
            this.$refs.form.reset();
          }
        });
      }
    }
  }
</script>

@SimoTod
Copy link
Collaborator

SimoTod commented May 10, 2020

👍
You probably want to disable the button on click and reenable it on error or success as well. It will save you from figuring out why you have duplicate subscriptions in the future (yeah some people double click buttons 😂).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants