Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Info about this Paste: https://stackoverflow.com/q/50342677/9217760
- * Start copying below this comment, whichever applies.
- */
- [HTML]
- <ol>
- <li>Click on the <i>restGetTest()</i> button and see the response.</li>
- <li>Edit the "grad" value and click on the <i>restPostTest()</i> button.</li>
- <li>Repeat step #1 and see if the "grad" value has changed.</li>
- </ol>
- <input id="grad" value="<?= esc_attr( get_field( 'grad', 'user_4' ) ) ?>">
- <div id="rest-res">Response goes here.</div>
- <p>
- <button onclick="restGetTest(this)">restGetTest()</button>
- <button onclick="restPostTest(this)">restPostTest()</button>
- </p>
- [JS/AJAX]
- <script>
- function restAjaxGo( btn, method, url, data ) {
- btn.blur();
- btn.disabled = true;
- jQuery( '#rest-res' ).html( 'Loading..' );
- return jQuery.ajax( url, {
- type: method,
- dataType: 'json',
- 'data': data
- }).fail( function( xhr, status, error ){
- jQuery( '#rest-res' ).html( 'Error "<i>' + status + '</i>": ' + error );
- }).always( function( xhr ){
- btn.disabled = false;
- var res;
- if ( xhr && 'object' === typeof xhr && /^\{/.test( xhr.responseText ) ) {
- try {
- res = JSON.parse( xhr.responseText );
- } catch ( err ) {}
- }
- if ( res && res.code ) {
- jQuery( '#rest-res' ).html(
- 'Error ' + res.code + ': ' + res.message
- );
- } else {
- console.log( xhr );
- jQuery( '#rest-res' ).html( 'Try again later?' );
- }
- });
- }
- function restGetTest( btn ) {
- restAjaxGo( btn, 'GET', '/wp-json/wp/v2/users/', {
- _wpnonce: '<?= wp_create_nonce( 'wp_rest' ) ?>',
- include: 4,
- per_page: 1
- }).done( function( res ){
- jQuery( '#rest-res' ).html( res[0].grad );
- });
- }
- function restPostTest( btn ) {
- restAjaxGo( btn, 'POST', '/wp-json/wp/v2/users/4', {
- _wpnonce: '<?= wp_create_nonce( 'wp_rest' ) ?>',
- grad: jQuery( '#grad' ).val()
- }).done( function( res ){
- jQuery( '#rest-res' ).html( res.grad );
- });
- }
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement