mattyh88
mattyh88

Reputation: 1645

Uncaught ReferenceError: $ is not defined in Laravel 5.5 app

I have a main layout template for my Laravel 5.5 app that loads jQuery 3.2.1 (successfully) through CDN. I checked my developer 'network' tab to make sure that jQuery is loaded fine. (It is because I can see a 200 HTTP status code)

<html>
    <head>
        <title>My app - @yield('title')</title>
    </head>

    <body>
        <div class="container">
            @yield('content')
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
        </script>
    </body>
</html>

In a template, that extends my layout template, I've tried writing some jQuery to simply submit a form.

@extends('layouts.app')

@section('content')
    <form id="my-form" action="{{ route('item.store') }}">
        <input type="text" name="name" />
        <button id="my-submit-button" type="submit">Add</button>
    </form>

    <script>
        $(document).ready(function() {
            $("#my-form").submit(function(event) {
                event.preventDefault();
            });

            $("#my-submit-button").click(function() {
                axios.post('/items', {
                    name: 'item-name',
                })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            });
        });
    </script>
@endsection

The problem is: I keep seeing: "Uncaught ReferenceError: $ is not defined". What am I doing wrong?

Thanks!

Upvotes: 0

Views: 2765

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

This is happening because you are loading your code into the layout template with @yield('content') before you load the jQuery library with your script tag. Change your html to put the jquery link in the head tag above the code that will be using it.

<html>
<head>
    <title>My app - @yield('title')</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
</head>

<body>
    <div class="container">
        @yield('content')
    </div>

</body>

Upvotes: 3

Related Questions