Skip to content

Instantly share code, notes, and snippets.

@frontycore
Last active December 18, 2025 19:39
Show Gist options
  • Select an option

  • Save frontycore/2203f55753109bf5e317a37bc5a383cc to your computer and use it in GitHub Desktop.

Select an option

Save frontycore/2203f55753109bf5e317a37bc5a383cc to your computer and use it in GitHub Desktop.
WP AJAX fetch
(function() {
const data = new FormData();
data.append('action', 'fetch_action');
data.append('nonce', FETCH.nonce);
fetch(FETCH.ajax_url, {
method: "POST",
credentials: 'same-origin',
body: data
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
}());
<?php
define('NONCE_ACTION', 'fetch_nonce');
// Load JS
enqueue_js('fetch', 'fetch.js');
wp_localize_script('fetch', 'FETCH', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce(NONCE_ACTION)
]);
// Define AJAX action
function fetch_action()
{
$verified = isset($_POST['nonce']) && $_POST['nonce'] && wp_verify_nonce($_POST['nonce'], NONCE_ACTION);
// Processing
wp_send_json($_POST);
}
add_action('wp_ajax_fetch_action', 'fetch_action');
add_action('wp_ajax_nopriv_fetch_action', 'fetch_action');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment