Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created March 2, 2017 08:07
Show Gist options
  • Save fumikito/454810f84bd3d4457147b7ca524835ba to your computer and use it in GitHub Desktop.
Save fumikito/454810f84bd3d4457147b7ca524835ba 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>
@snade
Copy link

snade commented Sep 18, 2018

Hi,
there are two typos,
on line 8 'wp-adpi' shoul be 'wp-api',
and on line 20 wpApiSetting should be wpApiSettings
:)

@dealslama
Copy link

What if I'm sending post data from another website to WP data backend?

@shazahm1
Copy link

As a script dependency, I recommend using wp-api-request instead of wp-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 to wpApiSettings.root and wpApiSettings.nonce which is all you need to send a REST request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment