Skip to content

Instantly share code, notes, and snippets.

@byevhen2
Forked from phpbits/apiRequest.js
Last active September 9, 2024 07:19
Show Gist options
  • Save byevhen2/452c74147db1289f7b42f7118273165b to your computer and use it in GitHub Desktop.
Save byevhen2/452c74147db1289f7b42f7118273165b to your computer and use it in GitHub Desktop.
Using wp.apiRequest to access custom endpoints.
// See: wp-includes/js/api-request.js
// Returns a jqXHR object. See: https://api.jquery.com/jQuery.ajax/#jqXHR
wp.apiRequest({path: '/namespace/vendor/v1/config'})
.then(configOptions => console.log(configOptions));
// jqXHR object has method then(), but does not have methods catch() or
// finally(). Use fail() or always() instead
wp.apiRequest({path: '/namespace/vendor/v1/config'})
.done(configOptions => console.log(configOptions))
.fail((request, statusText) => {
if (request.responseJSON && request.responseJSON.message) {
console.error(request.responseJSON.message);
} else {
console.error(statusText);
}
})
always(() => console.log('Finish.'));
// Pass data to the request
wp.apiRequest({
path: '/namespace/vendor/v1/entity',
data: {
id: 17
}
})
.then(...);
// By default the type of the request is "GET"
wp.apiRequest({
path: '/namespace/vendor/v1/entity/delete',
type: 'POST',
data: {
id: 17
}
})
.then(...);
/*
* See also:
* https://api.jquery.com/jQuery.ajax/#data-types
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment