olivierGrech olivierGrech - 6 months ago 9
jQuery Question

Wordpress - registering a script depending on JQuery

I register and enqueue my script like this:

wp_register_script('api_script', plugins_url('api.js', __FILE__), array('jquery'));
wp_enqueue_script('api_script');


My api.js file consist only of a call to the
$.ajax
function :

$.ajax({
/*Stuff*/
});


However, I'm getting the following error:
TypeError: $ is undefined
.
Help please!

Answer

When writing javascript with jQuery for Wordpress you want to write "safe" jQuery functions by not using the dollar sign. You can use:

jQuery.ajax({
   /*Stuff*/
});

Or you can pass a dollar sign as a parameter like this:

(function($) {
   $.ajax({
      /*Stuff*/
   });
 })(jQuery);

And it then runs an anonymous function with a parameter passing the jQuery object.