Created
March 2, 2017 08:07
-
-
Save fumikito/454810f84bd3d4457147b7ca524835ba to your computer and use it in GitHub Desktop.
A typical jQuery request to WordPress REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
As a script dependency, I recommend using
wp-api-request
instead ofwp-api
unless you need the full wp-api + backbone + underscore to be loaded and ready for use otherwise you're just loading a bunch of stuff you do need.Using
wp-api-request
you still get access towpApiSettings.root
andwpApiSettings.nonce
which is all you need to send a REST request.