Trying to convert Kirby's Ajax tutorial to Vue/Axios

Hello,

I am currently learning Vue, and in the process I am trying to convert the https://getkirby.com/docs/cookbook/ajax-load-more tutorial, to Vue & Axios (https://github.com/axios/axios). I am totally new to those, so my code may be extremely bad…!

I used the exact same Kirby/php code as written in the tutorial, and added only the js. My problem is that Kirby doesn’t seem to find that the request I am making is through Ajax in the projects.php controller:

if(r::ajax() && get('offset') && get('limit')) {

and always fetches the projects specified in the else part.

The js:

new Vue({
  el: '.main',

  mounted() {
    this.projects = this.$el.querySelector('.projects')
    this.limit = parseInt(this.projects.dataset.limit)
    this.offset = this.limit
    this.page = this.projects.dataset.page + '.json'
  },

  methods: {
    fetchProjects() {
      axios.get(this.page, {
        params: {
          limit: this.limit,
          offset: this.offset
        }
      })
      .then(response => {
        this.projects.insertAdjacentHTML("beforeend", response.data.html)
        this.offset += this.limit
        if (response.data.more === false) { this.$el.querySelector('.load-more').style.display = 'none' }
      })
    }
  }
});

What am I doing wrong??

I haven’t used Axios with Kirby yet but on a recent project I used Javascript XHR and had to manually include the HTTP header X_REQUESTED_WITH to the request.

Kirby r::ajax() checks if the value of that HTTP header is XMLHttpRequest. You can add it to Axios with:

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
1 Like

That was it! Thank you very much!