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

Include the JavaScript file and pass the variables

It's important to pass the variables when including the JavaScript file.

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');
Code language: PHP (php)


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

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) { const 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); }); } }());
Code language: JavaScript (javascript)

No jQuery was used for this snippet.


Get the plugin 👇

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> if you need to.