imacrayon / alpine-ajax

An Alpine.js plugin for building server-powered frontends.
https://alpine-ajax.js.org
MIT License
558 stars 11 forks source link

Global event listeners #76

Closed nkev closed 3 months ago

nkev commented 3 months ago

Thank you for this awesome HTMX alternative for AlpineJS!

I saw the ajax.configure() method in the docs for setting headers:

Alpine.plugin(ajax.configure({
  headers: { 'X-CSRF-Token': 'mathmatical!' }
}))

... but I'm looking for a way to send a 'Request ID' token (similar to a CSRF) with EVERY request, for all HTTP methods. I want to set it in one place using JS to add it to ALL AJAX requests in different ways, e.g. as a form element for POST requests but query string for GET/HEAD requests.

Is there a way for example, to set a global ajax:before JS function event handler?

imacrayon commented 3 months ago

Yeah, I don’t think there’s currently an easy way to do this. We could add an ajax:send event what would let you modify the request before sending it. That would parallel nicely with ajax:merge which lets you change the merge step.

nkev commented 3 months ago

Is there a reason why we cannot handle existing declarative attribute events like ajax:before in global functions, so they can be shared by many HTML elements?

imacrayon commented 3 months ago

You can do this in v0.7 now:

document.addEventListener('ajax:send', function (event) {
  if (event.detail.method === 'GET') {
    event.detail.action = event.detail.action + '?=request_id=xxx'
  } else {
    event.detail.body.append('request_id', 'xxx')
  }
})
nkev commented 2 months ago

Thank you! This opens up a lot of doors... :)