ElliotSchmelliot ElliotSchmelliot - 7 months ago 243
Javascript Question

jQuery $.cookie is not a function

I am trying to set a cookie using jQuery:

$.cookie("testCookie", "hello");
alert($.cookie("testCookie"));


But when I load my page, I receive the error "$.cookie is not a function". Here is what I know:


  • I have downloaded the jQuery cookie plugin here.

  • I am linking to jQuery and THEN the cookie plugin.

  • Both jQuery and jQuery.cookie are loading correctly with 200 OKs.



I have looked at several other answers (here and here among others), to which most people suggested renaming the cookie.js file. I have renamed my cookie file "jquery.cookeee.js" but the results are the same.

Any ideas on what is going on here?

If it helps, I am creating a web application in MVC 4.

Answer

If anyone else stumbles upon the $.cookie is not a function problem, here are all the possible problems/solutions I have come across:

  • The cookie plugin was not downloaded. $.cookie is not a standard jQuery function and the plugin needs to be downloaded here. Make sure to include the appropriate <script> tag where necessary (see next).
  • When including the cookie script, make sure to include jQuery FIRST, then the cookie plugin.

i.e. your head might contain:

<script src="~/Scripts/jquery-2.0.3.js" type="text/javascript"></script>

and THEN

<script src="~/Scripts/jquery_cookie.js" type="text/javascript"></script>
  • In some cases, renaming the file to something that does NOT include ".cookie" has fixed this error, apparently due to web server issues. By default, the downloaded script is titled "jquery.cookie.js" but try renaming it to something like "jquery_cookie.js" as shown above. More details on this problem are here.
  • Lastly (this was my problem), make sure you aren't including jQuery more than once. If you are, it is possible that 1. jQuery loads correctly 2. The cookie plugin loads correctly 3. Finally your second inclusion of jQuery overwrites the first and destroys the cookie plugin.

For anyone using ASP.Net MVC projects, be careful with the default javascript bundle inclusions; they can be hard to find sometimes. My second inclusion of jQuery was within one of my global layout pages under the line @Scripts.Render("~/bundles/jquery"). I personally prefer not rendering bundles and just linking to javascript as needed.

Cheers and special thanks to Kevin B for the help on this one.