How to use WordPress admin-ajax with Fetch API

I wrote a small WordPress Plugin to track post page views.

The plugin uses JavaScript because if you cache your pages, like I do, doing page view tracking with PHP does not work. Using JS allows you to cache the HTML output and still track every page view.

I wanted to share how to use the admin-ajax with the JavaScript Fetch API


As you can see we need to send at least the nonce which is sent from the PHP file when including the JS.

The ajax_url is also set in our PHP and used here directly.

Please also notice the credentials 'same-origin'

(function () { const $el = document.getElementById('wp-pageviews'); if ($el && $el.dataset.postid) { var data = new FormData(); data.append( 'action', 'wp_pageviews_add_pageview' ); data.append( 'nonce', wp_pageviews_ajax.nonce ); data.append( 'is_user_logged_in', wp_pageviews_ajax.is_user_logged_in ); data.append( 'is_single', wp_pageviews_ajax.is_single ); data.append( 'postid', $el.dataset.postid); fetch(wp_pageviews_ajax.ajax_url, { method: "POST", credentials: 'same-origin', body: data }) .then((response) => response.json()) .then((data) => { if (data) { $el.innerText = data; } }) .catch((error) => { console.log('[WP Pageviews Plugin]'); console.error(error); }); } }());

No jQuery was used for this snippet.

Include the JS and pass the variables

It's important to pass the variables when including the JS file you just created.

As you can see below I'm sending ajax_url and nonce. I also send other parameters that are used for my particular use case (tracking page views). You don't need those.

function wp_pageviews_scripts() { if(is_single() && !is_user_logged_in()){ wp_enqueue_script('wp_pageviews_scripts', wp_pageviews_url . '/main.js', '', '1.1.0', true); wp_localize_script( 'wp_pageviews_scripts', 'wp_pageviews_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'wp-pageviews-nonce' ), 'is_user_logged_in' => is_user_logged_in(), 'is_single' => is_single() ) ); } } add_action('wp_enqueue_scripts', 'wp_pageviews_scripts');


Get the plugin πŸ‘‡

Leave a Reply

Add <code> Some Code </code> by using this tags.