Skip to content

doRestRequest

Mark Howells-Mead edited this page Oct 9, 2019 · 1 revision

JavaScript function

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);
				}
			}
		});
	}
};

Usage

var parseResults = function(results){
	console.log(results);
};
doRestRequest('wp/v2/posts/12345/', 'GET', parseResults);

PHP for WordPress

wp_localize_script('main', 'wpAPISettings', [
	'root' => esc_url_raw(rest_url()),
	'nonce' => wp_create_nonce('wp_rest')
]);
Clone this wiki locally