Friday, March 29, 2024

Referencing WordPress’s Native Ajax Handler in JavaScript

 10/29/13

Ajax is already built into the core WordPress (WP) administration screens. It’s also the technology behind the auto-save functionality on post and page editing screens. AJAX requests go through wp-admin/admin-ajax.php. Despite the name, you don’t have to have adminsitrator privledges to use it. What you do need is a reference to the admin-ajax.php file. This article describes how to add our JavaScript files to the page in such a way that we can reference the path to admin-ajax.php on the server.

The wp_enqueue_script() Function

The preferred way to add JS files to the page is to use the wp_enqueue_script() function. It links a script file to the generated page at the right time according to the script dependencies. Here’s its signature, along with input parameters:

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
  • $handle: This is a string that used as a handle for other Worpress functions, like wp_localize_script().
  • $src: An optional parameter that describes the full path to the JavaScript file. Since you never want to hard-code paths, you should use a built-in helper function for this purpose. For instance, the includes_url() points to the “public_html/wp-includes” folder. It can be concatenated as follows: includes_url() . 'js/myajax.js'.
  • $deps: Another optional parameter that lists the handles of all the registered scripts that must be loaded before this script. It expects an Array, so even one item must be converted into an Array of one element. Our script will make use of jquery’s excellent Ajax capabilities.
  • $ver: An optional string specifying the script version number. It’s used by WP to ensure that the correct version is sent to the client, regardless of caching. The number is concatenated to the end of the path as a query string, as in myajax.js?ver=1.6.0. If no version is specified or is set to false, then WP automatically adds a version number equal to the current version of WordPress you are running.
  • $in_footer: Traditionally, JavaScript elements were placed in the HEAD of the HTML document. Lately, an emerging trend has been to relocate them just before the &ly;/body> end tag. This helps the page content load before scripts. If this parameter is true, the script is placed at the end of the page. Note that doing so requires the theme to include the wp_footer() template tag.

The wp_localize_script() Function

The wp_localize_script() function is not only useful for localizing script variables and data, but it also has a neat ability to make PHP data available to your Javascript. Here’s its signature, along with input parameters:

wp_localize_script( $handle, $object_name, $l10n );
  • $handle: The $handle refers directly to the script that you enqueue using wp_enqueue_script(). Hence, it’s value must exactly match the first parameter of your wp_enqueue_script() call.
  • $object_name: This is what the Javascript object containing the data will be named. Ideally, this name really should should be unique to both the script and to the plugin or theme. Moreover, the name should start with an upper case letter and use camelCase as JavaScript object naming conventions dictate.
  • $l10n: A single or multi-dimensional array containing the data.

There is only one sure-fire way to send server-side objects to the client, and that is to serialize it as a string. Better still, WP converts it into a JSON-formatted string so that it can easily be reconstituted on the client-side.

The Script Enqueuing Code and Resulting Output

Here is how wp_enqueue_script() and wp_localize_script() functions can be used to reference a JavaScript file called “myajax.js” and create an object that it will be able to reference to call the “admin-ajax.php” script on the server:

wp_enqueue_script( 'admin_url', includes_url() . 'js/myajax.js', array( 'jquery' ) );
$admin_url = array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'admin_url', 'AdminURL', $admin_url  );

The above code results in the following HTML output:

<script type='text/javascript'>
/* <![CDATA[ */
var AdminURL = {"ajaxUrl":"http://robgravelle.com/wp-admin/admin-ajax.php"};
/* ]]> */
</script>
<script type='text/javascript' src='http://robgravelle.com/wp-includes/js/myajax.js?ver=3.6.1'></script>

The Ajax Call

In the myajax.js file, there is a jQuery-syntax Ajax call. It references the AdminURL object that was appended to the page via the wp_localize_script() call. On the server, the admin-ajax.php process expects an action to bind the call to. We’ll be talking more about that in the next article on the server-side code. You may also supply an option data property if you want to pass information to the server. You can either send the data as a JSON by setting the contentType to “application/json” or by simply stringifying the object to a JSON-formatted string, as I did here. Success and failure callbacks handle both eventualities:

var result = $('#result'),
    myData = { color: 'blue', date:  new Date() };
$.post(
	    AdminURL.ajaxUrl,
   	  {
       		// here we declare the parameters to send along with the request
       		// this means the following action hooks will be fired:
       		// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
       		action: 'myajax-submit',

       		// other parameters can be added along with "action"
       		data: JSON.stringify(myData)
    	},
    	function(res,code,xhr) {
          if (res) {
              results.html(res); 
          }
          else {  
              results.html('No data was returned from the server.');
          }
    	}
   ).fail(function() {    
	     results.html('An Ajax error occurred.' );  
});

Conclusion

In today’s article, we saw how to add our JavaScript files to the page using the wp_enqueue_script() and wp_localize_script() functions. The follow-up will deal with how to hook your server-side callbacks to the admin-ajax.php script.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured