Home > OS >  update x-for from Ajax - Alpine Js
update x-for from Ajax - Alpine Js

Time:03-14

How can I tell Alpine to update the x-for from the server. In another word, How to do force update in AlpineJs.

<select id="branches" name="branches" x-data="ajax" >
    <option value="" disabled selected="">Choose</option>
    <template x-for="branche in branches">
        <option :value="branche.ID" x-text="branche.Branch_name"></option>
    </template>
</select>
    document.addEventListener('alpine:init', () => {
        Alpine.data('ajax', () => ({
            async branches() {
                return await $.post("path-url", {
                    tb: "branches"
                }, (data) => {
                    return data;
                });
            }
        }))
    })

CodePudding user response:

Assuming $.post is from jQuery:

<select id="branches" name="branches" x-data="getBranches()">
  <option value="" disabled selected="">Choose</option>
  <template x-for="branch in branches">
    <option :value="branch.ID" x-text="branch.Branch_name"></option>
  </template>
</select>

<script>
document.addEventListener('alpine:init', () => {
  Alpine.data('getBranches', () => ({
    branches: [],

    init() {
      $.post("path-url", {
        tb: "branches"
      }, (data) => {
        this.branches = data
      })
    }
  }))
})
</script>

We used the init() method to get the data, that executes before rendering the component. You don't have to "force" the update, just mutate a reactive Alpine.js data variable and Alpine.js will update the DOM shortly after.

  • Related