Skip to content

Instantly share code, notes, and snippets.

@monecchi
Forked from fumikito/request.php
Created September 8, 2018 05:29
Show Gist options
  • Save monecchi/4ad0e74ee291cd8c8149ce24bd7aa577 to your computer and use it in GitHub Desktop.
Save monecchi/4ad0e74ee291cd8c8149ce24bd7aa577 to your computer and use it in GitHub Desktop.
A typical jQuery request to WordPress REST API
<?php
/**
* Regsiter script
*/
add_action( 'wp_enqueue_scripts', function() {
// Set dependency to wp-api, which has nonce and endpoint root.
wp_enqueue_script( 'api-handler', '/path/to/api-handler.js', [ 'jquery', 'wp-adpi' ], '1.0', true );
} );
// Below is the content of api-handler.js
?>
<script>
(function($){
$('.button').click(function(){
var $button = $(this);
// e.g. Add loading classs
$button.addClass('loading');
// Endpoint from wpApiSetting variable passed from wp-api.
var endpoint = wpApiSetting.root + 'hametuha/v1/friend/';
$.ajax({
url: endpoint,
method: 'POST', // POST means "add friend" for example.
beforeSend: function(xhr){
// Set nonce here
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
// Build post data.
// If method is "delete", data should be passed as query params.
data: {
foo: 'var',
hoge: 'fuga'
}
}).done(function(response){
// Do something.
}).fail(function(response){
// Show error message
alert( response.responseJSON.message );
}).always(function(){
// e.g. Remove 'loading' class.
$button.removeClass('loading');
});
});
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment