Skip to content

Instantly share code, notes, and snippets.

@otakupahp
Last active February 21, 2021 15:57
Show Gist options
  • Save otakupahp/b53966d488b59b70153572b01ee7841c to your computer and use it in GitHub Desktop.
Save otakupahp/b53966d488b59b70153572b01ee7841c to your computer and use it in GitHub Desktop.
WordPress Ajax done correctly
<?php
# After enquequing the JS add this localization to add the nonce and other variables
$params = [
'action' => 'your_action',
'wp_nonce' => wp_create_nonce( 'wp_ajax_nonce' ),
'error' => __('There was an error with the Ajax call. Please try again later'),
];
wp_localize_script( 'custom_ajax_params', 'wp_globals', $params );
## ***********************************
add_action('wp_ajax_{your_action}', 'your_ajax_function');
function your_ajax_function() {
# Check nonce
check_ajax_referer( 'wp_ajax_nonce', 'security' );
// Do ajax action
}
/* global ajaxurl, wp_globals */
$.ajax({
cache: false,
type: "POST",
url: ajaxurl, // variable set on WP backend
data: {
/** @param {{wp_nonce, action}} woo_globals */
'action': 'your_action', // defined as the hook action "wp_ajax_{your_action}"
'security': wp_globals.wp_nonce, // wp_globals set via *wp_localize_script*
'id': id // add any addition
},
beforeSend: function (qXHR, settings) {
// Show loader
},
success: function (data) {
// Do action
},
error: function (xhr, ajaxOptions, thrownError) {
/** @param {{error}} woo_globals */
let result = (xhr.responseText === -1) ? wp_globals.error : xhr.responseText;
// show error
},
complete: function () {
// hide loader
}
});
@otakupahp
Copy link
Author

wp_ajax_{your_action} < is used for logged-in users
wp_ajax_nopriv_{your_action} < is used for NON logged-in users

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment