I want to make an Ajax call using Axios in Laravel 10 with Vite (I don’t use VueJs).
I get the error "axios is not defined".
My view :
<x-app-layout>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
<div class="p-4 sm:p-8 bg-white dark:bg-gray-800 shadow sm:rounded-lg">
hello world
</div>
</div>
</div>
<script>
axios.get("{{route('scann','xxx')}}"
).then(function(rep){
console.log(rep)
})
</script>
</x-app-layout>
in the layout I have included css and js before closing header with :
@vite(['resources/css/app.css', 'resources/js/app.js'])
app.js :
import './bootstrap';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
bootstrap.js :
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
2
Answers
It’s likely that
app.js
isn’t loaded until after the script tag in your view (Vite scripts aretype="module"
by default, so loading is deferred). Try waiting until the DOM is loaded:Defining global variables and inlining scripts are not good practices, but Blade and alpine.js both seem to encourage doing that.
If your app isn’t too big, maybe you can put everything in app.js (in, imported from, indirectly imported from, whatever as long as it’s in the build system’s output app.js file).