Last active
December 18, 2025 19:39
-
-
Save frontycore/2203f55753109bf5e317a37bc5a383cc to your computer and use it in GitHub Desktop.
WP AJAX fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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)); | |
| }()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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