Getting Started with Axios and WordPress


When working with modern Javascript like Vue.JS, a common thing is sending and receiving data via ajax. While this could be handled with jQuery, I’d recommend using Axios which is a modern standalone library for handling ajax requests. Axios can be enqueued just like any other Javascript library.

wp_enqueue_script( 'axios', 'https://unpkg.com/axios/dist/axios.min.js' );

The following PHP is an example taken from CaptainCore of a custom WordPress REST API endpoint. Any PHP returned with the REST API is automatically converted to JSON. That means data immediately usable within Javascript.

// Custom endpoint for CaptainCore site
register_rest_route(
	'captaincore/v1', '/customers/', array(
		'methods'       => 'GET',
		'callback'      => 'captaincore_customers_func',
		'show_in_index' => false
	)
);

function captaincore_customers_func( $request ) {

	$customers = new CaptainCore\Customers();
	$all_customers = array();

	foreach( $customers->all() as $customer ) {
		$all_customers[] = ( new CaptainCore\Customer )->get( $customer );
	}

	return $all_customers;

}

Data can be fetched from the above endpoint /wp-json/captaincore/v1/customers using the following Javascript. Passing the wpApiSettings.nonce allows the request to be verified by an authenticated logged in user. Useful when you want to only return info based on is_user_logged_in().

axios.get(
	'/wp-json/captaincore/v1/customers', {
		headers: {'X-WP-Nonce':wpApiSettings.nonce}
	})
	.then(response => {
		this.customers = response.data;
	});

WordPress behaves a little different with POST requests.

QS.js is a little helper to keep the code the same. Enqueuing QS is as simple as.

wp_enqueue_script( 'qs', 'https://unpkg.com/qs/dist/qs.js' );

The Qs.stringify will turn the data into serializing parameters. This allows us to build up the request in Javascript very similar to a jQuery post request. This would be a sample post request.

var data = {
	action: 'captaincore_ajax',
	post_id: site.id,
	command: 'usage-breakdown'
};

self = this;

axios.post( ajaxurl, Qs.stringify( data ) )
	.then( response => {
		self.dialog_usage_breakdown.response = response.data;
	})
	.catch( error => console.log( error ) );

The PHP on the other end of the request might look as follows.

function captaincore_ajax_action_callback() {
	global $wpdb; // this is how you get access to the database

	$post_id = intval( $_POST['post_id'] );
	$cmd     = $_POST['command'];
	$value   = $_POST['value'];

	// Checks permissions
	if ( ! captaincore_verify_permissions( $post_id ) ) {
		echo 'Permission denied';
		wp_die(); // this is required to terminate immediately and return a proper response
		return;
	}
	
	if ( $cmd == 'usage-breakdown' ) {

		$usage_breakdown = get_field( "usage_breakdown", $post_id );
		echo json_encode( $usage_breakdown ) ;

	}

	wp_die(); // this is required to terminate immediately and return a proper response

}

References