skip to Main Content

I’m working on a Laravel project and have trouble getting my JavaScript to run.
Just for testing purposes, I wrote a function called "ShowAlert", which are supposed to just display a simple alert screen with an OK button. But when I click the button to run this function, it shows the following error in the console:
Uncaught ReferenceError: ShowAlert is not defined

I have two separate JS files, one is the standard "app.js" which is located in the resources/js folder. In the same folder, I created a separate file called "mycode.js". My app.js file looks like this:

import './bootstrap';
import './mycode.js';

In the mycode.js file, I created the function using the window object, since I’ve read that JS code sometimes is not found because it has been written in the wrong scope. I don’t know if I’m doing this write, please tell me in that case. 🙂
The mycode.js file looks like the following:

window.ShowAlert = function()
{
    alert("Hello world!");
    }

Here is the head of the resources/views/layouts.app file which imports the JavaScript:

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">
        <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])

    
      
</head>

In a separate view, which extends the layout file above, I am calling the JS function like this:

<button onclick="ShowAlert()">Show alert</button>

Any help with this will be greatly appreciated!

All the best!

2

Answers


  1. First, you can import files to app.js without the extension, just a tip:

    import './mycode';
    

    I tried to replicate your issue, but it works just fine, for the JS function I did it like this:

    window.ShowAlert = () => {
        alert('Hello World');
    }
    

    Using a button like yours:

    <button onclick="ShowAlert()">Show Alert</button>
    

    For me, I repeat, it’s working fine. Make sure you’re running Vite:

    npm run dev
    

    The only way I could replicate your problem was trying to run it without Vite running, and took me a few minutes cause at first, I didn’t even consider it as a possibility. If you want to build your app instead of constantly have Vite running, what I don’t recommend in development for obvious reasons, you can try:

    npm run build
    
    Login or Signup to reply.
  2. change javascript code like:

    function ShowAlert() {
     alert('alert text');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search