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 :

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

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

Related posts

Leave a Reply

1 comment

  1. 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.