views:

85

answers:

3

I made a small example HTML page to get JQuery's getJSON method working. It looks like below (sorry for the sloppiness, this was just a proof of concept to then later add into a larger project):

<script type="text/javascript">

function test() {   
$.getJSON("http://api.flickr.com/services/rest/?&amp;method=flickr.people.getPublicPhotos&amp;api_key=e999b3a5d47d013b780e8ac255c86266&amp;user_id=24579658@N03&amp;format=json&amp;jsoncallback=?",    
                function(data){
                      $.each(data.photos.photo, function(i,photo){
     $("<img/>").attr("src", "http://farm5.static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg").appendTo("#images2");
    //alert();
        if ( i == 6 ) return false;
      });
});

}

I would then call that method when something was clicked using

<script type="text/javascript">

                            $(function() {
                                $("#yo").click(test);
                            });
    </script>

This worked fine in a project where the only JS I included was JQuery and these were the only functions. However, once I added it to my other project, it through errors. The other project has some mootools libraries included which I thought might've been doing it. However, even after completely removing the mootools stuff and just using this jquery stuff, I still get the error below:

ReferenceError: $ is not defined

I do have other javaScripts included such as a google one and some other ones I've made, but they don't use JQuery or Mootools. Can anyone explain why I'd be getting this error?

+1  A: 

$ is not defined means that jQuery is not linked to the $ variable at the point of the error. This could be for one of two reasons:

  1. jQuery used to be set as the $ variable, but no longer is. You may have called jQuery.noConflict(), for instance.
  2. You have not yet defined jQuery. This may be because you have placed this script above the call to the jQuery library. Make sure that the first script you reference is the jQuery source.
lonesomeday
The first script I am referencing is the jQuery library. When you say used to be set as "$" do you mean that I don't have to use the $ anymore?If I take out the $ and then add jQuery.noConflict(); before the getJson call, I get the following error:Uncaught ReferenceError: jQuery is not definedOtherwise if I remove the noconflict line and the $, I get:Uncaught TypeError: Object function (el, nc){ return document.id(el, nc, this.document); } has no method 'getJSON'
joshholat
When the jQuery library is loaded, it sets $ to be a reference to the library. You can change this if you want to by using jquery.noConflict(). Other libraries (such as mootools) also use the $ variable, and having several libraries will result in naming conflicts as a result. Have you removed the reference to the mootools library?
lonesomeday
`Uncaught TypeError: Object function (el, nc){ return document.id(el, nc, this.document); } has no method 'getJSON'` -> document.id is a mootools function ($ maps to it if undefined previously). this means jquery has failed to define it itself. are you using mootools greater than 1.2.2? anyway, irrelevant, you said the reference exception is also happening w/o mootools at all.
Dimitar Christoff
A: 

You have a conflict with the $ variable as mootools is also attempting to use the variable. Only 1 can use it at a time.

Check out jQuery.noConflict() -> http://api.jquery.com/jquery.noconflict/

You need to call no conflict before any attempt to use jQuery is made. You have a few optons with using jQuery.noConflict(). One is to just reassign and use a jQuery specific variable everywhere:

$jQ = jQuery.noConflict();

Now you can use $jQ

$jQ( "#yo" ).click( test );

When dealing with a separate JS file you can use a litte JS functionality to allow the '$' variable to mean "jQuery" within your file:

(function($) {
  function test() {   
  $.getJSON("http://api.flickr.com/services/rest/
  &method=flickr.people.getPublicPhotos&api_key=e999b3a5d47d013b780e8ac255c86266&user_id=24579658@N03&format=json&jsoncallback=?",    
                  function(data){
                        $.each(data.photos.photo, function(i,photo){
      $("<img/>").attr("src", "http://farm5.static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg").appendTo("#images2");
      //alert();
          if ( i == 6 ) return false;
        });
  });
})(jQuery);

That little beauty is called a self-invoking anonymous function. We are defining the $ as an input parameter, but passing in jQuery to ensure that is what the $ variable means.

Andrew Wirick
he said it breaks even when taking out mootools. mootools does NOT try to take over the $ (unless old old version) - if $ is defined by something else, mootools reverts to `document.id` instead. if it _were_ to take it over, it most certainly won't come off as undefined.
Dimitar Christoff
+2  A: 

It certainly sounds as if some of the additional code you have brought in has undefined the $ symbol. In fact, it is possible you have included some code that calls jQuery's noConflict function, which specifically undefines $.

jQuery, in essence, defines it like this:

$ = jQuery;

That means that you could replace the $ symbol in your code with "jQuery," for example:

jQuery.getJSON(...

or

jQuery(function() {
    jQuery("#yo").click(test);
});

Of course, the $ symbol shortcut certainly is handy. It would be a shame to give that up, so you could redefine it to stand in for "jQuery" once again. You would not want it to break any of your other, non-jQuery JavaScript, though, so the safe way to reestablish the $ shortcut would be to wrap all of your own code in closures. The lone parameter to each closure function would be "$" and the argument passed to each closure would "jQuery." For example:

(function($) {
        function test() {   
            $.getJSON("http://api.flickr.com/services/rest/?&amp;method=flickr.people.getPublicPhotos&amp;api_key=e999b3a5d47d013b780e8ac255c86266&amp;user_id=24579658@N03&amp;format=json&amp;jsoncallback=?",    
                        function(data){
                              $.each(data.photos.photo, function(i,photo){
             $("<img/>").attr("src", "http://farm5.static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg").appendTo("#images2");
            //alert();
                if ( i == 6 ) return false;
              });
        });
})(jQuery);

Notice that the anonymous function closure has the parameter $, so inside the entire function the $ will have the value you pass to the anonymous function. Next, notice that at the end of the function definition, we immediately invoke the function we have just defined and we pass jQuery as the argument. That means that inside the closure, but only inside the closure, $ is now a shortcut for jQuery.

One final note, you can deliberately turn off jQuery's use of the $ symbol by calling jQuery.noConflict() (see http://api.jquery.com/jQuery.noConflict/). If you will be using other JavaScript code beyond just your code and jQuery, it is a good idea to call that function after you have loaded all of your JavaScript files, then use the closure technique described above, so that you can safely continue to the $ shortcut in your own code.

dgvid