518

I have a simple jquery click event

<script type="text/javascript">
    $(function() {
        $('#post').click(function() {
            alert("test"); 
        });
    });
</script>

and a jquery reference defined in the site.master

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>

I have checked that the script is being resolved correctly, I'm able to see the markup and view the script directly in firebug, so I must be being found. However, I am still getting:

$ is not defined

and none of the jquery works. I've also tried the various variations of this like $(document).ready and jQuery etc.

It's an MVC 2 app on .net 3.5, I'm sure I'm being really dense, everywhere on google says to check the file is referenced correctly, which I have checked and checked again, please advise! :/

Selim Yildiz
  • 4,224
  • 6
  • 14
  • 25
Paul Creasey
  • 26,917
  • 10
  • 51
  • 88
  • 6
    Do you actually see the jquery-1.3.2.js asked for and loaded with HTTP200 response code, if you inspect the page load with Fiddler tool? – naivists Feb 03 '10 at 19:59
  • 22
    is your script executing before jquery? – Surya Feb 03 '10 at 20:00
  • 2
    Can you view source and click on js link. Seems like your jquery is not loaded on page. Try Firebug Console Screen to See errors Try also http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js in your script tag – nemke Feb 03 '10 at 20:01
  • 2
    Is your script firing before the jquery source is loaded? – Dave Bacher Feb 03 '10 at 20:02
  • 1
    @Surya/Dave, i've gone home now, so i'll check it out again tomorrow, and come back and post, but i think that probably the issue, :/ how embarassing! – Paul Creasey Feb 03 '10 at 20:21
  • Please provide more information about the source code. There's too many unknowns to provide the correct answer! – Ben Rowe Feb 04 '10 at 04:48
  • Post a link tot he actual page... fastest way. – jeffkee Feb 03 '10 at 20:46
  • intranet only im afraid. – Paul Creasey Feb 03 '10 at 21:17
  • I prefer using firebug or similar tool to check if the jquery.js is being downloaded or not. Check if there are any 404's. – Teja Kantamneni Feb 03 '10 at 20:02
  • Just a note, when we applied a security certificate (https) jquery could not load in because we are are using aspnetcdn to load it instead of doing so from our site. I know this is not the answer for this situation, but I found this question looking for an answer to our question.. Google search : https jquery is undefined stackoverflow.com – Brett Weber Dec 18 '13 at 16:50
  • For those using Electron you might want to check this answer: https://stackoverflow.com/questions/32621988/electron-jquery-is-not-defined – Emir Apr 15 '20 at 10:14

35 Answers35

606

That error can only be caused by one of three things:

  1. Your JavaScript file is not being properly loaded into your page
  2. You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
  3. You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.

First of all, ensure, what script is call properly, it should looks like

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

and shouldn't have attributes async or defer.

Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.

Make sure all jQuery javascript code is being run inside a code block such as:

$(document).ready(function () {
  //your code here
});

This will ensure that your code is being loaded after jQuery has been initialized.

One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.

Note: If you're loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.

Denis Tsoi
  • 5,957
  • 5
  • 26
  • 46
Mike Trpcic
  • 23,821
  • 7
  • 71
  • 111
  • 195
    Regarding your code block, `$(document)` won't work either unless you have a script tag including jQuery before that statement... – PatrikAkerstrand Dec 07 '10 at 15:07
  • 3
    I would like to add that I had the same issue as the OP and my problem was that using https with jquery's library doesn't work so well. – Mike Cheel Oct 20 '11 at 13:36
  • 21
    (function($){ })(jQuery); – JackMahoney Apr 04 '13 at 04:40
  • 2
    @Patrik: See my answer for a solution using a scripts section in the view. This way jquery will be loaded first and $ is properly defined. – angularsen Dec 03 '13 at 15:01
  • Related to point 1. Sometimes clearing the browser cache helps, because browser will ignore the changes if a bad jquery file was cached. – cfillol Mar 28 '14 at 08:45
  • That error can also be cause by a fourth thing: 4. You have jQuery setup in compatibility mode. In WordPress jQuery is loaded this way by default. – metaColin Aug 15 '14 at 21:20
  • 1
    Check if you have async on the script as well, thats what caused the problem in my case. – Anders Jan 03 '17 at 13:56
  • Surprising there's no mention that the jQuery file might be being loaded properly but *after* the inline code that's relying on it, see the other answers for that... – rogerdpack Jan 22 '17 at 04:32
214

It could be that you have your script tag called before the jquery script is called.

<script type="text/javascript" src="js/script.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

This results as $ is not defined

Put the jquery.js before your script tag and it will work ;) like so:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript" src="js/script.js"></script>
Elmo
  • 5,743
  • 15
  • 64
  • 132
Hanky Panky
  • 2,149
  • 1
  • 11
  • 2
  • 1
    This is a great response. I tried it and it worked for me. I'm using VS 2013 and ASP.net. Do you know how I can make javascript load before the page loads automatically in asp.net or do I have to reference javascript this way in all my files? – Pat May 22 '15 at 21:42
  • To add to your answer. In ASP.net you can go into Shared\_Layout.cshtml ` ` – Pat May 26 '15 at 03:37
  • @pat and make sure you write your code inside a `@section Scripts` tag – Marc Aug 11 '15 at 20:29
  • Please update answer to use HTTPS and consider use of SPI http://devdocs.io/html/attributes#integrity-attribute – Josh Habdas Jun 01 '17 at 05:19
75

First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.

<script src="jquery.min.js"></script>

This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.

Then you need to use one of the two solutions below

(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code, 
// or outside the document ready, enter code here
 })(jQuery); 

or

jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});

please be aware that many times $(document).ready(function(){//code here}); will not work.

Andrew Killen
  • 1,564
  • 20
  • 21
  • 2
    "jQuery is not defined". It exists after page load however. – Paul Totzke Mar 22 '16 at 16:52
  • Not sure if this is a question or a statement, but, I would check you make the call for the jQuery script before you try to use it. It sounds like your loading it in the footer and calling things higher up the page. – Andrew Killen Mar 23 '16 at 15:02
  • Sorry, I thought this was a technique that you could use the scripts in any order. Yes I was using this in the body section in the MVC style. mycode.js then jQuery.js are the last 2 things on the page. – Paul Totzke Mar 23 '16 at 17:00
  • No worries Paul, I've edited the solution to include 'you must... load first'. :) – Andrew Killen Mar 24 '16 at 07:31
  • Does this fix the problem of "My scripts are in the right order but the scripts are loaded in a different order". I remember doing something like this at 4 years ago but I can't remember what problem it solved. – Paul Totzke Mar 24 '16 at 12:36
  • This is right, you have to basically load jquery "before" any content that wants to use it, including any inline scripts that run right after page load. At the bottom would allow content to load slightly more quickly, ref: http://stackoverflow.com/questions/1860482/when-do-you-choose-to-load-your-javascript-at-the-bottom-of-the-page-instead-of). The work around option is to only use vanilla javascript for inline scripts, but that's tricky since you'll have two code paths, one that can use jQuery and one that can't. – rogerdpack Jan 22 '17 at 04:31
55

If the jQuery plugin call is next to the </body>, and your script is loaded before that, you should make your code run after window.onload event, like this:

window.onload = function() {
  //YOUR JQUERY CODE
}

`

so, your code will run only after the window load, when all assets have been loaded. In that point, the jQuery ($) will be defined.

If you use that:

$(document).ready(function () {
  //YOUR JQUERY CODE
});

`

the $ isn't yet defined at this time, because it is called before the jQuery is loaded, and your script will fail on that first line on console.

Bruno Peres
  • 2,295
  • 1
  • 18
  • 18
dandapereira
  • 637
  • 5
  • 6
  • Generally a bad idea to tie into window.unload. It will effectively be the only event that runs!!! – Rudi Strydom Apr 25 '16 at 08:48
  • Note: Remember you can only assign one window.onload function, if you assign another function to it, the previous will not be executed. – Bruno Peres May 25 '16 at 15:25
29

I just did the same thing and found i had a whole lot of

type="text/javacsript"

So they were loading, but no further hint as to why it wasn't working. Needless to say, proper spelling fixed it.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
George R
  • 3,284
  • 3
  • 30
  • 36
  • **Moderator note**: the typo in this post is *deliberate*, to illustrate a point. Please do not edit the post to “correct” this. – Martijn Pieters Apr 06 '18 at 22:55
23

Use a scripts section in the view and master layout.

Put all your scripts defined in your view inside a Scripts section of the view. This way you can have the master layout load this after all other scripts have been loaded. This is the default setup when starting a new MVC5 web project. Not sure about earlier versions.

Views/Foo/MyView.cshtml:

// The rest of your view code above here.

@section Scripts 
{ 
    // Either render the bundle defined with same name in BundleConfig.cs...
    @Scripts.Render("~/bundles/myCustomBundle")

    // ...or hard code the HTML.
    <script src="URL-TO-CUSTOM-JS-FILE"></script>

    <script type="text/javascript">
      $(document).ready(function () {

        // Do your custom javascript for this view here. Will be run after 
        // loading all the other scripts.            
      });
    </script>
}

Views/Shared/_Layout.cshtml

<html>
<body>
    <!-- ... Rest of your layout file here ... -->

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Note how the scripts section is rendered last in the master layout file.

angularsen
  • 7,134
  • 1
  • 60
  • 76
  • 2
    Note: View sections are not supported in partial views by design. – Adam Naylor May 21 '15 at 10:37
  • This is what I had to do for my fix....and I should have known better to use the @Scripts in the first place but forgot about it until I looked for a fix. – Caverman Feb 12 '18 at 19:08
14

As stated above, it happens due to the conflict of $ variable.

I resolved this issue by reserving a secondary variable for jQuery with no conflict.

var $j = jQuery.noConflict();

and then use it anywhere

$j( "div" ).hide();

more details can be found here

Naveed Abbas
  • 1,061
  • 12
  • 35
12

make sure you really load jquery this is not jquery - it's the ui!

  <script language="JavaScript" 
    src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js">
  </script>

This is a correct script source for jquery:

 <script language="JavaScript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Josh Habdas
  • 6,370
  • 2
  • 53
  • 55
Wolfgang Fahl
  • 12,097
  • 9
  • 75
  • 150
9

It means that your jQuery library has not been loaded yet.

You can move your code after pulling jQuery library.

or you can use something like this

window.onload = function(){
  // Your code here
};  
Nesar
  • 5,252
  • 2
  • 18
  • 17
  • This fires after the DOM has loaded, but not when controls, javascript and other programs running in the background has loaded. A time delay would need to be used for this to work. – Fandango68 Nov 22 '16 at 00:13
7

Are you using any other JavaScript libraries? If so, you will probably need to use jQuery in compatibility mode:

http://docs.jquery.com/Using_jQuery_with_Other_Libraries

tambler
  • 2,889
  • 2
  • 21
  • 25
6

after some tests i found a fast solution , you can add in top of your index page:

<script>
$=jQuery;
</script>

it work very fine :)

Mimouni
  • 3,427
  • 3
  • 24
  • 32
4

It sounds like jQuery isn't loading properly. Which source/version are you using?

Alternatively, it could a be namespace collision, so try using jQuery explicitly instead of using $. If that works, you may like to use noConflict to ensure the other code that's using $ doesn't break.

the Tin Man
  • 150,910
  • 39
  • 198
  • 279
4

I got the same error message when I misspelled the jQuery reference and instead of type="text/javascript" I typed "...javascirpt". ;)

Brian Mains
  • 49,697
  • 35
  • 139
  • 249
alan
  • 49
  • 1
3

That error means that jQuery has not yet loaded on the page. Using $(document).ready(...) or any variant thereof will do no good, as $ is the jQuery function.

Using window.onload should work here. Note that only one function can be assigned to window.onload. To avoid losing the original onload logic, you can decorate the original function like so:

originalOnload = window.onload;
window.onload = function() {
  if (originalOnload) {
    originalOnload();
  }
  // YOUR JQUERY
};

This will execute the function that was originally assigned to window.onload, and then will execute // YOUR JQUERY.

See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.

Kyle McVay
  • 378
  • 2
  • 12
2

I use Url.Content and never have a problem.

<script src="<%= Url.Content ("~/Scripts/jquery-1.4.1.min.js") %>" type="text/javascript"></script>
Peter Lillevold
  • 32,442
  • 7
  • 92
  • 127
mdm20
  • 4,375
  • 1
  • 19
  • 24
2

I had the same problem and resolved it by using

document.addEventListener('DOMContentLoaded', () => {
 // code here
});
Walmac
  • 153
  • 1
  • 6
2

In the solution it is mentioned - "One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described."

For avoiding this -

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():

1

Just place jquery url on the top of your jquery code

like this--

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>

<script type="text/javascript">
    $(function() {
        $('#post').click(function() {
            alert("test"); 
        });
    });
</script>
vikrantx
  • 469
  • 5
  • 20
1

I had the same problem and it was because my reference to the jQuery.js was not in the tag. Once I switched that, everything started working.

Anthony

Anthony
  • 27
  • 1
1
  1. Check the exact path of your jquery file is included.

    <script src="assets/plugins/jquery/jquery.min.js"></script>

if you add this on bottom of your page , please all call JS function below this declaration.

  1. Check using this code test ,

    <script type="text/javascript">
    /***
     * Created by dadenew
     * Submit email subscription using ajax
     * Send email address
     * Send controller
     * Recive response
     */
    $(document).ready(function() { //you can replace $ with Jquery
    
      alert( 'jquery working~!' );
    });
    

Peace!

Daniel Adenew
  • 6,825
  • 6
  • 48
  • 70
1

I had this problem once for no apparent reason. It was happenning locally whilst I was running through the aspnet development server. It had been working and I reverted everything to a state where it had previously been working and still it didn't work. I looked in the chrome debugger and the jquery-1.7.1.min.js had loaded without any problems. It was all very confusing. I still don't know what the problem was but closing the browser, closing the development server and then trying again sorted it out.

cedd
  • 1,561
  • 1
  • 16
  • 33
0

When using jQuery in asp.net, if you are using a master page and you are loading the jquery source file there, make sure you have the header contentplaceholder after all the jquery script references.

I had a problem where any pages that used that master page would return '$ is not defined' simply because the incorrect order was making the client side code run before the jquery object was created. So make sure you have:

<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
    <asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
</head>

That way the code will run in order and you will be able to run jQuery code on the child pages.

0

In my case I was pointing to Google hosted JQuery. It was included properly, but I was on an HTTPS page and calling it via HTTP. Once I fixed the problem (or allowed insecure content), it fired right up.

Anthony
  • 4,965
  • 9
  • 45
  • 78
0

After tried everything here with no result, I solved the problem simply by moving the script src tag from body to head

Spring
  • 8,976
  • 26
  • 96
  • 175
  • This is not an answer to the question. Please do not spam SO with unhelpful answers which bring nothing to the topic. If you believe your experience might help others, either put it as a short comment or provide a proper answer with full explanation of the solution. – Dharman Nov 07 '18 at 23:17
0

I was having this same problem and couldn't figure out what was causing it. I recently converted my HTML files from Japanese to UTF-8, but I didn't do anything with the script files. Somehow jquery-1.10.2.min.js became corrupted in this process (I still have no idea how). Replacing jquery-1.10.2.min.js with the original fixed it.

Gavin
  • 5,796
  • 2
  • 44
  • 67
0

it appears that if you locate your jquery.js files under the same folder or in some subfolders where your html file is, the Firebug problem is solved. eg if your html is under C:/folder1/, then your js files should be somewhere under C:/folder1/ (or C:/folder1/folder2 etc) as well and addressed accordingly in the html doc. hope this helps.

sc123
  • 1
0

I have the same issue and no case resolve me the problem. The only thing that works for me, it's put on the of the Site.master file, the next:

<script src="<%= ResolveUrl("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>
<script src="<%= ResolveUrl("~/Scripts/bootstrap/js/bootstrap.min.js") %>" type="text/javascript"></script>

With src="<%= ResolveUrl("")... the load of jQuery in the Content Pages is correct.

amelian
  • 385
  • 1
  • 5
  • 13
0

I had a very similar issue. In my C# MVC application, JQuery was not being recognized. I needed to move the @Scripts.Render("~/bundles/jquery") from the bottom of my _Layout.cshtml file to the head of the section. Also make sure you have grabbed Jquery as a Nuget package if you are using visual studio!

<head>
    @Scripts.Render("~/bundles/jquery")
</head>
BHOW
  • 129
  • 3
0

There is a way to make it automatically load up javascript before the rest of the code runs.

Go into Views\Shared_Layout.html and add the following

<head>
  <*@ Omitted code*@>
  <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
Pat
  • 404
  • 1
  • 7
  • 18
0

if script tag has defer attribute it show the error

Uncaught ReferenceError: $ is not defined

and must remove the attribute defer from script tag

AbdulAhmad Matin
  • 925
  • 1
  • 13
  • 26
0

This is the common issue to resolve this you have to check some point

  1. Include Main Jquery Library
  2. Check Cross-Browser Issue
  3. Add Library on TOP of the jquery code
  4. Check CDNs might be blocked.

Full details are given in this blog click here

Anju Batta
  • 84
  • 4
0

Something that I didn't find here, but did happen to me. Make sure you don't have the jQuery slim version included, as that version of the jQuery library doesn't include the Ajax functionality.

The result is that "$" works, but $.get for example returns an error message stating that that function is undefined.

Solution: include the full version of jQuery instead.

David van Driessche
  • 5,833
  • 2
  • 21
  • 38
0

I came across same issue, and it resolved by below steps. The sequence of the scripts should be as per mentioned below

    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script src="~/Scripts/jquery-ui.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>

This sequence was not correct for my code, I corrected this as per the above and it resolved my issue of Jquery not defined.

0

We have the same problem....but accidentally i checked folder properties and set something...

You have to check the properties of each folders that you're accessing..

  1. right click folder
  2. 'permissions' tab
  3. set the folder access : OWNER: create and delete files GROUP: access files OTHERS: access files

I hope that this is the solution......

McGarnagle
  • 96,448
  • 30
  • 213
  • 255
-1

u just add at starting of your page

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

and check your src link in a any browser address bar, if you are getting some code then this will work for you. asif

asifaftab87
  • 985
  • 22
  • 26