doRestRequest
Mark Howells-Mead edited this page Oct 9, 2019
·
1 revision
Based on original code by Marc.
window.pendingAjax = [];
var doRestRequest = function(restRoute, method, callback) {
if (window.pendingAjax.indexOf(restRoute) < 0) {
window.pendingAjax.push(restRoute);
if (!method) {
method = 'GET';
}
$.ajax({
url: wpAPISettings.root + restRoute,
type: method,
cache: false,
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpAPISettings.nonce);
},
success: function(response) {
if (typeof callback === 'function') {
callback(response);
}
},
error: function(jqXHR) {
console.error(jqXHR);
},
complete: function() {
var index = window.pendingAjax.indexOf(restRoute);
if (index > -1) {
window.pendingAjax.splice(index, 1);
}
}
});
}
};
var parseResults = function(results){
console.log(results);
};
doRestRequest('wp/v2/posts/12345/', 'GET', parseResults);
wp_localize_script('main', 'wpAPISettings', [
'root' => esc_url_raw(rest_url()),
'nonce' => wp_create_nonce('wp_rest')
]);
Mark Howells-Mead | https://permanenttourist.ch and https://sayhello.ch/ | Wiki since 2016
Use this code freely, widely and for free. Provision of this code provides and implies no guarantee.
Please respect the GPL v3 licence, which is available via http://www.gnu.org/licenses/gpl-3.0.html