├── .config └── rome.rjson ├── es6-wp-ajax-demo.css ├── uninstall.php ├── .github └── FUNDING.yml ├── es6-wp-ajax-demo.js ├── README.md └── es6-wp-ajax-demo.php /.config/rome.rjson: -------------------------------------------------------------------------------- 1 | // For configuration documentation see http://romefrontend.dev/#project-configuration 2 | name: "es6-wp-ajax-demo" 3 | root: true 4 | -------------------------------------------------------------------------------- /es6-wp-ajax-demo.css: -------------------------------------------------------------------------------- 1 | #es6-demo { 2 | display: flex; 3 | justify-content: center; 4 | align-items: center; 5 | 6 | height: 100vh; 7 | 8 | } 9 | 10 | #es6-demo-output, #es6-demo-input { 11 | font-family: monospace; 12 | font-size: 3em; 13 | /* height: 5rem; 14 | margin-left: 1rem; */ 15 | } -------------------------------------------------------------------------------- /uninstall.php: -------------------------------------------------------------------------------- 1 | { 12 | // Wait util the webpage is loaded 13 | let button = document.getElementById("es6-demo-input"); // The form button 14 | let output = document.getElementById("es6-demo-output"); // The output area 15 | 16 | button.onclick = event = async (event) => { 17 | // Fire the event when the button is clicked. 18 | event.preventDefault(); 19 | 20 | const self = event.currentTarget; // "this" button 21 | const data = new FormData(); 22 | data.append("action", "es6_ajax_action"); // wp ajax action, more info at https://developer.wordpress.org/plugins/javascript/enqueuing/#ajax-action 23 | data.append("nonce", pluginES6WPAjax.nonce); // set the nonce, added at https://github.com/soderlind/es6-wp-ajax-demo/blob/master/es6-wp-ajax-demo.php#L75 24 | data.append("sum", self.dataset.sum); // get the value from the data-sum attribute in the form. 25 | 26 | const url = pluginES6WPAjax.ajaxurl; // set the ajax url, added at https://github.com/soderlind/es6-wp-ajax-demo/blob/master/es6-wp-ajax-demo.php#L76 27 | try { 28 | const response = await fetch( 29 | url, 30 | { 31 | // POST the data to WordPress 32 | method: "POST", 33 | credentials: "same-origin", 34 | body: data, 35 | }, 36 | ); 37 | 38 | const res = await response.json(); // read the json response from https://github.com/soderlind/es6-wp-ajax-demo/blob/master/es6-wp-ajax-demo.php#L57 39 | if (res.response === "success") { 40 | self.dataset.sum = res.data; // Update the data-sum attribute with the incremented value. 41 | output.innerHTML = res.data; // Display the updated value. 42 | console.log(res); 43 | } else { 44 | console.error(res); 45 | } 46 | } catch (err) { 47 | console.error(err); 48 | } 49 | }; 50 | }, 51 | ); 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WordPress Ajax using native JavaScript 2 | 3 | >A more modern approach is [WordPress REST using native JavaScript](https://github.com/soderlind/es6-wp-rest-demo) 4 | 5 | ## Prerequisite 6 | 7 | You should know [how WordPress does Ajax](https://developer.wordpress.org/plugins/javascript/ajax/). 8 | 9 | ## Look at the code 10 | 11 | I recommend that you [take a look at the code](https://github.com/soderlind/es6-wp-ajax-demo/blob/master/es6-wp-ajax-demo.js), it's not hard to understand what's happening. 12 | 13 | ### JavaScript (ES6) 14 | 15 | First I create the `data` object using [FormData](https://javascript.info/formdata). 16 | 17 | ```javascript 18 | const data = new FormData(); 19 | data.append('action', 'es6_ajax_action'); 20 | data.append('nonce', pluginES6WPAjax.nonce); 21 | data.append('sum', self.dataset.sum); 22 | ``` 23 | 24 | Then I use [aync/await](https://javascript.info/async-await) with [fetch](https://javascript.info/fetch) to do the ajax call. 25 | 26 | ```javascript 27 | const response = await fetch(url, { 28 | method: 'POST', 29 | credentials: 'same-origin', 30 | body: data 31 | }); 32 | 33 | const res = await response.json(); 34 | if (res.response == 'success') { 35 | self.dataset.sum = res.data; 36 | output.innerHTML = res.data; 37 | console.log(res); 38 | } else { 39 | console.error(res); 40 | } 41 | ``` 42 | 43 | Note: [previous release](https://github.com/soderlind/es6-wp-ajax-demo/releases/tag/1.0.2) use [fetch().then().catch()](https://github.com/soderlind/es6-wp-ajax-demo/blob/1.0.2/es6-wp-ajax-demo.js#L23-L39) 44 | 45 | 46 | Note 2: Why move from `fetch().then().catch()` to `async/await`? Because V8 .. 47 | 48 | > [favor async functions and await over hand-written promise code](https://v8.dev/blog/fast-async#conclusion) 49 | > - V8 dev blog 50 | 51 | 52 | ### PHP 53 | 54 | The PHP code is more or less the same as you would do when using jQuery, but I've added the `fetch` [polyfill](https://en.wikipedia.org/wiki/Polyfill_(programming)) 55 | 56 | ```php 57 | // Load the fetch polyfill, url via https://polyfill.io/v3/url-builder/. 58 | wp_enqueue_script( 'polyfill-fetch', 59 | 'https://polyfill.io/v3/polyfill.min.js?features=fetch', 60 | [], 61 | ES6_WP_AJAX_DEMO_VERSION, 62 | true 63 | ); 64 | ``` 65 | 66 | ## Demo 67 | 68 | Not very exciting, the demo increments a number when you click on a button. 69 | 70 | ## Installation 71 | 72 | - [Download the plugin](https://github.com/soderlind/es6-wp-ajax-demo/archive/master.zip) 73 | - Install and activate the plugin. 74 | - Add the `[es6demo]` shortcode to a page. 75 | - Click on the `+` button to increment the number. 76 | 77 | ## Copyright and License 78 | 79 | es6-wp-ajax-demo is copyright 2019 Per Soderlind 80 | 81 | es6-wp-ajax-demo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. 82 | 83 | es6-wp-ajax-demo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 84 | 85 | You should have received a copy of the GNU Lesser General Public License along with the Extension. If not, see http://www.gnu.org/licenses/. 86 | 87 | -------------------------------------------------------------------------------- /es6-wp-ajax-demo.php: -------------------------------------------------------------------------------- 1 | 0 ] ) : 0; 44 | if ( isset( $sum ) ) { 45 | $response['response'] = 'success'; 46 | $sum = ++$sum; 47 | $response['data'] = $sum; 48 | update_option( 'es6demo_sum', $sum ); 49 | } else { 50 | $response['response'] = 'failed'; 51 | $response['data'] = 'something went wrong ...'; 52 | } 53 | } else { 54 | $response['response'] = 'failed'; 55 | $response['message'] = 'invalid nonse'; 56 | } 57 | echo wp_json_encode( $response ); 58 | wp_die(); 59 | } 60 | 61 | /** 62 | * Add Scripts. 63 | * 64 | * @return void 65 | */ 66 | function wp_scripts() { 67 | $ajaxurl = get_ajax_url(); 68 | $url = plugins_url( '', __FILE__ ); 69 | 70 | // Load fetch polyfill, url via https://polyfill.io/v3/url-builder/. 71 | wp_enqueue_script( 'polyfill-fetch', 'https://polyfill.io/v3/polyfill.min.js?features=fetch', [], ES6_WP_AJAX_DEMO_VERSION, true ); 72 | wp_enqueue_script( 'es6-wp-ajax', $url . '/es6-wp-ajax-demo.js', [ 'polyfill-fetch' ], ES6_WP_AJAX_DEMO_VERSION, true ); 73 | $data = wp_json_encode( 74 | [ 75 | 'nonce' => wp_create_nonce( 'es6_wp_ajax_nonce' ), 76 | 'ajaxurl' => $ajaxurl, 77 | ] 78 | ); 79 | wp_add_inline_script( 'es6-wp-ajax', "const pluginES6WPAjax = ${data};" ); 80 | } 81 | 82 | /** 83 | * Get the Ajax URL. 84 | * 85 | * @return string 86 | */ 87 | function get_ajax_url() : string { 88 | // multisite fix, use home_url() if domain mapped to avoid cross-domain issues. 89 | $http_scheme = ( is_ssl() ) ? 'https' : 'http'; 90 | if ( home_url() !== site_url() ) { 91 | $ajaxurl = home_url( '/wp-admin/admin-ajax.php', $http_scheme ); 92 | } else { 93 | $ajaxurl = site_url( '/wp-admin/admin-ajax.php', $http_scheme ); 94 | } 95 | return $ajaxurl; 96 | } 97 | 98 | /** 99 | * Demo Form 100 | */ 101 | add_shortcode( 'es6demo', __NAMESPACE__ . '\es6demo_form' ); 102 | 103 | /** 104 | * Create Demo Form. 105 | * 106 | * @param array $args Shortcode arguments. 107 | * @return string 108 | */ 109 | function es6demo_form( $args ) { 110 | $o = ''; 111 | $sum = get_option( 'es6demo_sum', 0 ); 112 | $o .= '