Skip to content

Instantly share code, notes, and snippets.

@byevhen2
Forked from phpbits/apiRequest.js
Last active October 6, 2022 15:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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