Advertisement
5ally

stack-overflow-50342677

May 23rd, 2018
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. /**
  2.  * Info about this Paste: https://stackoverflow.com/q/50342677/9217760
  3.  * Start copying below this comment, whichever applies.
  4.  */
  5.  
  6.  
  7. [HTML]
  8.  
  9. <ol>
  10.   <li>Click on the <i>restGetTest()</i> button and see the response.</li>
  11.   <li>Edit the "grad" value and click on the <i>restPostTest()</i> button.</li>
  12.   <li>Repeat step #1 and see if the "grad" value has changed.</li>
  13. </ol>
  14.  
  15. <input id="grad" value="<?= esc_attr( get_field( 'grad', 'user_4' ) ) ?>">
  16. <div id="rest-res">Response goes here.</div>
  17.  
  18. <p>
  19.     <button onclick="restGetTest(this)">restGetTest()</button>
  20.     <button onclick="restPostTest(this)">restPostTest()</button>
  21. </p>
  22.  
  23.  
  24. [JS/AJAX]
  25.  
  26. <script>
  27. function restAjaxGo( btn, method, url, data ) {
  28.     btn.blur();
  29.     btn.disabled = true;
  30.  
  31.     jQuery( '#rest-res' ).html( 'Loading..' );
  32.  
  33.     return jQuery.ajax( url, {
  34.         type: method,
  35.         dataType: 'json',
  36.         'data': data
  37.     }).fail( function( xhr, status, error ){
  38.         jQuery( '#rest-res' ).html( 'Error "<i>' + status + '</i>": ' + error );
  39.     }).always( function( xhr ){
  40.         btn.disabled = false;
  41.  
  42.         var res;
  43.         if ( xhr && 'object' === typeof xhr && /^\{/.test( xhr.responseText ) ) {
  44.             try {
  45.                 res = JSON.parse( xhr.responseText );
  46.             } catch ( err ) {}
  47.         }
  48.  
  49.         if ( res && res.code ) {
  50.             jQuery( '#rest-res' ).html(
  51.                 'Error ' + res.code + ': ' + res.message
  52.             );
  53.         } else {
  54.             console.log( xhr );
  55.  
  56.             jQuery( '#rest-res' ).html( 'Try again later?' );
  57.         }
  58.     });
  59. }
  60.  
  61. function restGetTest( btn ) {
  62.     restAjaxGo( btn, 'GET', '/wp-json/wp/v2/users/', {
  63.         _wpnonce: '<?= wp_create_nonce( 'wp_rest' ) ?>',
  64.         include: 4,
  65.         per_page: 1
  66.     }).done( function( res ){
  67.         jQuery( '#rest-res' ).html( res[0].grad );
  68.     });
  69. }
  70.  
  71. function restPostTest( btn ) {
  72.     restAjaxGo( btn, 'POST', '/wp-json/wp/v2/users/4', {
  73.         _wpnonce: '<?= wp_create_nonce( 'wp_rest' ) ?>',
  74.         grad: jQuery( '#grad' ).val()
  75.     }).done( function( res ){
  76.         jQuery( '#rest-res' ).html( res.grad );
  77.     });
  78. }
  79. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement