Created
May 3, 2017 08:23
-
-
Save VicVicos/81550626cbbffaeb8d28f043031c0675 to your computer and use it in GitHub Desktop.
Ajax WP OOP habrahabr.ru/company/dataart/blog/271189/
This file contains hidden or 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
| abstract class AJAX_Handler { | |
| function __construct($action_name) { | |
| $this->init_hooks($action_name); | |
| } | |
| public function init_hooks($action_name) { | |
| add_action('wp_ajax_'.$action_name , array($this,'callback')); | |
| add_action('wp_ajax_nopriv_'.$action_name, array($this,'callback_nopriv')); | |
| } | |
| public function callback_nopriv() { | |
| $this->callback(); | |
| } | |
| abstract public function callback(); | |
| } |
This file contains hidden or 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
| new Something('do_something'); | |
| function js_variables() { | |
| $variables = array ( | |
| 'ajax_url' => admin_url('admin-ajax.php'), | |
| 'is_mobile' => wp_is_mobile() | |
| // Тут обычно какие-то другие переменные | |
| ); | |
| echo '<script type="text/javascript">window.wp_data = ' . json_encode($variables) . ';</script>'; | |
| } | |
| add_action('wp_head', 'js_variables'); |
This file contains hidden or 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
| jQuery(function($){ | |
| $.ajax({ | |
| type: "GET", | |
| dataType: 'json', | |
| url: window.wp_data.ajax_url, | |
| data: { | |
| action : 'do_something' | |
| }, | |
| success: function (response) { | |
| console.log('AJAX response : ',response); | |
| } | |
| }); | |
| }); |
This file contains hidden or 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 | |
| class Something extends AJAX_Handler | |
| { | |
| function callback () | |
| { | |
| wp_send_json_success(['test' => 'Works!']); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment