I try to implement Alpine JS within a existing page.
For that, I'm using the CDN version of Alpine, which I'm loading within my <head>:
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
Now I'm trying to access Alpine from a custom.js file, which is loaded automatically within the footer of my page:
Alpine.magic('post', function () {
return function (url, data = {}) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: JSON.stringify(data)
});
}
});
Within my content I tried this:
<div x-data>
<h1>Alpine Test</h1>
<button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>
By clicking the button, this error occurs:
Uncaught ReferenceError: $post is not defined
I've also tried it with window.Alpine, without success.
How can I add magic properties and stuff like that without using modules?
When you use the defer attribute the browser executes the script after the document parsing. You have to add the defer attribute to the custom.js script as well, or embed the magic definition within an alpine:init event listener block:
document.addEventListener('alpine:init', () => {
Alpine.magic('post', function () {
return function (url, data = {}) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: JSON.stringify(data)
});
}
});
})
This ensures that the magic definition happens only after the Alpine.js core is ready.