Last active
February 21, 2021 15:57
-
-
Save otakupahp/b53966d488b59b70153572b01ee7841c to your computer and use it in GitHub Desktop.
WordPress Ajax done correctly
This file contains 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 | |
# 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 | |
} |
This file contains 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
/* 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 | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wp_ajax_{your_action} < is used for logged-in users
wp_ajax_nopriv_{your_action} < is used for NON logged-in users