An in-depth guide on using Ajax with WordPress

jQuery for WordPress

jQuery is the most widely used tool on the Internet right now. It surpasses React, Vue, and others. Why? It’s just so damn easy to use. Yes, it has limitations. It’s slow on mobile compared to React. It’s not as easy to render the DOM as React and Vue. However, for simple use-cases, jQuery is still the library of choice.

In this chapter I’ll cover:

  • Namespacing
  • Public properties and functions
  • Private variables and functions

You may have your own preference on how to code your own jQuery scripts, but the examples I give are based on various painful experiences of trial and error (remember my drunk friend?). In my examples, I’m not going for creative programming; I’m going for readability.

Namespacing

For those not familiar with namespacing, let me give you a brief example.

Say that there are two plugins, both having the function of readCookie, which is not that uncommon since it is a very usable function name when trying to read the contents of a cookie via JavaScript. You’d have a naming conflict, and your browser console will start blowing up red, and other scripts may not be able to run.

Namespacing resolves this issue by enclosing the readCookie function inside of a unique name that can only be called from within the namespace.

The result? No conflicts. So how does one namespace?

Let’s start off with some basic jQuery starter code that will spit out an alert box after the page has finished loading.

jQuery( function( $ ) {
	alert( 'Hello World' );
} );

The above code is shorthand for when the document has finished loading. When it is finished loading, you should see an alert. An additional benefit is you can use the above code ad-Infinitum, unlike the selfish onLoad event (theme and plugin authors using the onLoad event are just asking to get trolled by other developers).

Notice also the $ symbol. It’s used for other JavaScript libraries, so the $ symbol is not that reliable. With the above technique, you can pass in the $ symbol and use it as shorthand for jQuery.

Here’s an example of quickly setting up a namespace.

jQuery( function( $ ) {
	$.my_script_namespace = {
		init: function() {
			alert( 'Hello World' );
		}
	};
	$.my_script_namespace.init();
} );

And let’s not forget to enqueue the script (the below example uses a WordPress theme).

add_action( 'wp_enqueue_scripts', 'my_plugin_prefix_enqueue_scripts' );
/**
 * Enqueue our scripts.
 */
function my_plugin_prefix_enqueue_scripts() {
	wp_enqueue_script(
		'my_plugin_prefix_handle',
		get_stylesheet_directory_uri() . '/js/my-plugin.js',
		array( 'jquery' ),
		'1.0.0',
		true
	);
}

One quick observation: we’re loading jQuery as a dependency in our wp_enqueue_script call.

Public Properties and Functions

Since we’re not creating a jQuery plugin per se, we’ll stray slightly from the “guidelines.”

There are certain variables, properties, and functions you will want others to be able to publicly call. Here’s an example of each type.

jQuery( function( $ ) {
	$.my_script_namespace = {
		init: function() {
			alert( 'Hello World' );
		},
		my_function: function( obj ) { /*public function my_function calling a private function */ 
			_my_function( $( obj ) );
		},
		vars: {} /* public vars object */
  
	};
	$.my_script_namespace.init();
} );

The init function is your publicly accessible initialization function call. You execute code directly inside the function (method?) without referencing other functions.

The my_function is another publicly accessible function. You can execute code, and call a private function (which we’ll declare later).

And vars is a variable declared as an empty object, which can be added to from an additional private variable of the same name (not declared yet).

Private Variables and Functions

Private variables and functions are necessary for when you don’t want other scripts to call your functions directly (use a property for indirect access).

A script with private variables and functions looks like this:

jQuery( function( $ ) {
	$.my_script_namespace = {
		init: function() {
			alert( 'Hello World' );
		},
		my_function: function( obj ) { /*public function my_function calling a private function */ 
			_my_function( $( obj ) );
		},
		vars: {} /* public vars object */
  
	};
	$.my_script_namespace.init();

	//Private variables/functions are declared outside of the namespace.
	
	var myvars = $.my_script_namespace.vars; //private variable
	function _my_function( obj ) { /*private function*/
		// my private code here.
	}
} );

Notice that our namespace ended before the declaration of the private functions and variables. Also note the commas separating the properties, functions, and variables in the namespace.

All of the functions and variables (that are private) are now within the scope of the jQuery ready enclosure. Since they exist only within the scope of the enclosure, you will be able to avoid the conflict of having duplicate JavaScript functions.

The beauty of this is that the namespaced functions can call in-scope functions. Furthermore, the private variables can reference the namespaced variables.

If you’ve been looking closely at the code, you’ll observe that nothing is being done here aside from the init function being called. The namespace is there, but nothing is really happening. It’s as if the namespace doesn’t exist (cue scary music).

Advanced users (such as other plugin authors) may need to call this from outside the original script. In this case, you’ll want to use the above script as a dependency, and use your own load event to call the script using the regular jQuery namespace.

jQuery( function( $ ) {
	jQuery.my_script_namespace.init();
} );

The result of the above code (assuming you’ve enqueued it properly) is an alert box will show when the init function is called.

Conclusion

While a crash-course in jQuery and JavaScript in general, we learned how to namespace our jQuery functions so they aren’t on a collision course with other global functions that may be declared.

We’ll go over more advanced JavaScript later, which will use more modern JavaScript syntax and possibly another dreaded third-party library (React, I’m looking at you).

The examples given are my personal guidelines from painful experience, but you’re welcome to experiment with your own techniques, including creating an actual jQuery plugin.

So the foundation has been laid. You know how to load scripts and styles properly. You know how to localize scripts and perform page detection. You also know some pretty nifty loading tricks.

Before we move to our first Ajax request (we’ll get there, I promise), let’s learn about nonces and WordPress security.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top