Skip to content

Instantly share code, notes, and snippets.

@sayedulsayem
Last active December 21, 2023 20:02
Show Gist options
  • Save sayedulsayem/9be611c41a67058d29f19bdf6adeae10 to your computer and use it in GitHub Desktop.
Save sayedulsayem/9be611c41a67058d29f19bdf6adeae10 to your computer and use it in GitHub Desktop.
WordPress Admin Ajax Request
<?php
wp_enqueue_script('handler', 'src_url', ['jquery'], '1.0.0', true);
wp_localize_script('handler', 'data', [
'ajaxUrl' => admin_url('wp-ajax.php'),
'nonce' => wp_create_nonce('ajax_nonce'),
]);
add_action('wp_ajax_action_name', 'action_name');
add_action('wp_ajax_nopriv_action_name', 'action_name');
function action_name() {
$nonce = isset($_REQUEST['nonce']) ? $_REQUEST['nonce'] : '';
if (!wp_verify_nonce($nonce, 'ajax_nonce')) {
exit('Unauthorized request');
}
wp_send_json(['status' => true]);
}
?>
<script>
jQuery.ajax({
url: data.ajaxUrl,
type: 'post', // get
data: {
action: 'action_name',
nonce: data.nonce,
data: formData,
},
dataType: 'json',
success(data) {
console.log(data);
},
error(req, status, error) {
console.log([req, status, error]);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment