Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincej's avatar
Level 15

Why $(document).ready(function() not work in a Blade view ?

I am not getting any errors like $ not defined. And I know that JS is working because if I do just a simple alert box it works:

        function myFunction()
          {
                alert("I am an alert box!")
            }

But as soon as I wrap document.ready around it , it fails - nothing happens, no error messages, nothing.

Why is this ?

0 likes
47 replies
thomaskim's avatar

You need to load jQuery before you run any jQuery script.

chrisgo's avatar

$ not defined means you do not have jquery loaded BEFORE your document.ready call

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$( document ).ready(function() {
    console.log( "ready!" );
});
</script>
vincej's avatar
Level 15

@Snapey

 <button onclick="myFunction()">Try it</button>

Yes - I have Jquery loaded, or else the alert would not work.

@chrisgo

I am not getting any errors like $ not defined. I do have JQuery loaded . definitly.

jlrdw's avatar

Looks like a regular javascript function not jquery.

Snapey's avatar

@vincej I assume there is some other reason why you want to place this function inside a jquery document ready function?

I assume it does not get called because it is now a private function inside your document ready function and so not visible to your on click.

when you say there are no errors, are you monitoring the browser console with browser development tools? I would expect myFunction not found when you click the button.

vincej's avatar
Level 15

I'm, using Bootstrap so I am pulling jquery off of googleapis at the top of my page.

I used the alert box only to prove that I have something working.

The actual code I am using is a very simple script I built on JsFiddle which works fine, but when deployed to my blade view it doesn't.

http://jsfiddle.net/vincej/st5t50f6/

thomaskim's avatar

If what you're saying is true, right-click, view page source, and copy/paste the compiled source code.

1 like
cimrie's avatar

@vincej

Without trying to be difficult, have you actually tried to paste the snippet I provided at the top of your view? If you try it and it works, then something else is wrong (for instance, bootstrap isn't being loaded properly).

Are you loading Bootstrap js files? jQuery is only a dependency of bootstrap.js and so won't be pulled in if you're only using the css stylesheets.

jimmck's avatar

Hi @vincej !! Can you post your Master Layout blade? Here is my 'kitchen sink' master blade. Its only job in life is to load jquery and then call other application blades.

<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="/assets/css/coverage.css">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Module Coverage</title>
</head>
    <body>
        <script src="/assets/js/jquery-1.10.2.js"></script>
        @yield('content')
        <script>
            (function () {
                var wrap = $('div#app');
                var melissa;
                //alert("Started...");
                //debugger;
                $('a').on('click', function (e) {
                    var href = $(this).attr('href');
                    wrap.load(href);
                    e.preventDefault();
                });
            })();
        </script>
    </body>
</html>

This way I know its always loaded first.

Jim

Snapey's avatar

OK, so this is what is happening.

If you just write myFunction and then have a button to call it, then its in the global document scope. It can find it and call the code.

When you wrap that function inside the jquery document ready block, it's now private to that function, and clicking the button will not call your function with the alert because its no longer in the global scope.

In your jsfiddle, ALL your functions are inside the document ready function

Do this to test;

 function myFunction()
 {
     alert("I am an alert box!")
 }

$(document).ready(function()
{
    myFunction();
)};

What I am expecting is that a) when you load the page, the alert box appears, and b) when you click the button the alert box appears.

And when working with javascript, open devtools on your browser so that you can see any errors in the console.

1 like
vincej's avatar
Level 15

@Clmrie I did as you asked and I pasted the snippet at the top of the page, commenting out the google api version.

No I am not loading Bootstrap js files.

@thomaskim I deleted my code and repasted the source again from fiddle just to make sure, and nope nada.

It should not affect things, however may I mention that I have the script inside the @extends // @stopassola

When I look at the source code for the page the script is at the bottom.

thomaskim's avatar

I meant copy/paste the code here. If you want us to help you, you really need to be posting code or we can only guess as to what's going on.

vincej's avatar
Level 15

@snapey - this makes sense, however when I tried to paste in your test I am getting errors around the *function myFunction() bit

jlrdw's avatar

Put your jquery after everything else on page, below body tag. Load it in head section. I never had any problem doing it that way.

echo '<td><a href="' . $dlink . '" class="delete">Delete</a>';

and

</body>
<script>

    $(function () {

        $(".delete").click(function (e) {
            if (!confirm('Are you sure?')) {
                e.preventDefault();
                return false;
            }
            return true;
        });
    });  ///end main
</script>

works like a champ.

Snapey's avatar
function myFunction() {
   alert("I am an alert box!");
 }

$(document).ready(function(){
  myFunction();
});

might have been a typo before

Snapey's avatar

Ignore all the ones saying you are loading jQuery wrong. That is not the issue. It's purely down to scope.

Don't forget WHY you might want to use $(document).ready(). It is to ensure that you don't start to manipulate the DOM with jquery before everything has loaded. One approach is to wrap all your DOM manipulation in this function. The other is to put jquery after the body has loaded.

In your case (certainly with this test) you are not doing any DOM manipulation so its not necessary to use this at all.

The sample code in your jsfiddle DOES need the DOM to be ready because you are attaching onBlur events to the form fields. If you just went ahead and ran that code as soon as it was encountered on the page then the form elements might not have even been loaded by that point.

vincej's avatar
Level 15

looks like the site could not take the input !

I can't remove it / or fix it !

thomaskim's avatar

@vincej

Bootstrap's JavaScript file depends on jQuery so you should be loading jQuery before bootstrap, not the other way around. Also, you are using jQuery 3, which is in the alpha stage. Bootstrap depends on jQuery 1.9+ or 2.* so you should change the ordering/scripts like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

Edit: Sorry for the spamming on page 2, but because of the code rendering issues, I needed to spam it so this can be shown properly on page 3.

chrisgo's avatar

@vincej this is really very basic stuff and not related to Blade at all. Your error is html/css/js (client-side) so make sure you can do that first.

Follow these steps

  • Create a file called test.htm beside your index.php file (in the public folder)
<html>
<head>
   <title>Test HTML Page</title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
   <script>
   $(document).ready(function()
   {
     myFunction();
   });
   function myFunction()
   {
      alert("I am an alert box!")
   } 
   </script>
</head>
<body>
TEST HTML PAGE
</body>
</html>

  • Pull this up on your browser, see if it works

  • Once you know what the HTML needs to look like, go back to your Blade template and keep doing a View Source until the HTML is 100% the same

vincej's avatar
Level 15

Glad to see it fixed. I could not delete my post so I tweeted Jeffrey.

For the record I did have my jQuery source loaded at the very top of the page during all my testing. However, @clmrie was very keen to see me replace it with his recommended api which I place in error at the bottom. 5 minutes later the site crash.

I very much appreciate all the effort and advice you have all offered. It is not taken for granted. if I may I will have a good look at this tomorrow .

vincej's avatar
Level 15

Firstly - I have it working ... almost. A very Big Thank you to all those who helped out and stuck with it.

So what was wrong ?? Where things went wrong was that I built my Laravel form using the same ID's as the test script.

The consequence was that when I ran the script into the Laravel view the output from the Jquery appeared in neither place leading me to believe that the script was flawed or the view was flawed. Well I guess the view was flawed. A dumb ass mistake which can frustrate the hell out of anyone. I have to admit that I have spent my life with back end systems and I hate JS / JQuery and have made every effort to avoid it - so I am really bad it.

I still have 1 problem: The output from my Jquery ( SubTotal / Tax / Total ) needs to appear in the input field of the form. Then those values will be grabbed with all the rest and sent to the DB. So to illustrate:

 <div class=" form-group">
       <div class="col-sm-2 col-sm-offset-8 col-md-2 col-md-offset-6">{!! Form::label('total', 'Total:') !!}</div>
        <div class="col-sm-4 col-md-4">{!! Form::text('total', 'JQuery VALUES NEED TO APPEAR HERE', ['class'=>'form-control ']) !!}</div>
</div>

I have hunted and googled and have not yet found a satisfactory answer. Any ideas ??

Many thanks !

vincej's avatar
Level 15

@jimmck - Hi Jim - thanks for that. However, I do not see how that helps me. The values I am passing in are not Laravel values from the DB. They are the products of the Jquery script.

cimrie's avatar

@vincej

You would need to add an id tag or other unique CSS selector to the text input. The API for Form::text is: text(string $name, string $value = null, array $options = array()) (found here: http://laravel.com/api/4.2/Illuminate/Html/FormBuilder.html#method_text )

For instance:

<div class="col-sm-4 col-md-4">{!! Form::text('total', '', ['class'=>'form-control ', 'id' => 'myUniqueInputId']) !!}</div>

Then use that in jQuery (wherever you are performing your calculations or ajax request to get the data in the first place would be a good place):

$('#myUniqueInputId').value('JQuery VALUES NEED TO APPEAR HERE');
Next

Please or to participate in this conversation.