WordPress: Hướng dẫn sử dụng ajax frontend
Tiếp tục series về wordpress thì hôm nay mình sẽ hướng dẫn các bạn khai báo vào sử dụng kỹ thuật ajax ngoài giao diện trong wordpress mời các bạn đón xem.
1. Khai báo khi sử dụng ajax ngoài frontend wordpress
1 2 3 4 5 |
add_action( 'wp_enqueue_scripts', 'ajax_scripts' ); function ajax_scripts() { wp_enqueue_script( 'ajax_custom_script', get_stylesheet_directory_uri() . '/includes/ajax-javascript.js', array('jquery') ); wp_localize_script( 'ajax_custom_script', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); } |
2. Vào folder file: includes/ajax-javascript.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var sl_date = $(this).val(); $.ajax({ url: frontendajax.ajaxurl, data: { 'action':'getpostevent_ajax_request', /* Tên function xử lý*/ 'sl_date' : sl_date /* Biến giá trị được gửi đi */ }, success:function(data) { $('#event-meeting').html(''); $('#event-meeting').html(data); $loading.hide(); }, error: function(errorThrown){ console.log(errorThrown); /* Hiển thị thông báo lỗi ra console */ } }); /* alert(value); return value*/ |
3. Function nhận và xử lý dữ liệu:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
function getpostevent_ajax_request() { // The $_REQUEST contains all the data sent via ajax if ( isset($_REQUEST) ) { $date = $_REQUEST['sl_date']; $arrdate = explode('-',$date); $year = $arrdate[0]; $month = $arrdate[1]; $day = $arrdate[2]; $args = array( 'post_type' => 'post', 'category_name ' => 'calendar', 'date_query' => array( array( 'year' => $year, 'month' => $month, 'day' => $day, ), ), 'orderby' => 'date', 'order' => 'DESC', ); $posts = get_posts( $args ); $html = '<input type="hidden" id="datepicker" readonly>'; foreach($posts as $post){ $html .= '<label for="datepicker">'.$post->post_title.'</label> <span class="date-event">'.date("d. m. Y",strtotime($post->post_date)).'</span> <p>'.$post->post_content.'</p>'; } $html .= "<script> showDateConfig(); selectDateEvent(); </script>"; $response = '<div class="meeting-content"> <div class="block-datepicker"> <div id="container"></div> </div> <div class="block-date-good "> <div class="block-date-good-result"> '.$html.' </div> <div id="ajax-loader" class="hide text-center"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> <span class="sr-only">Loading...</span></div> </div> </div>'; echo $response; //echo $query->request; } // Always die in functions echoing ajax content die(); } add_action( 'wp_ajax_getpostevent_ajax_request', 'getpostevent_ajax_request' ); //Fix bug Admin ajax request return 0 with die() add_action('wp_ajax_nopriv_getpostevent_ajax_request', 'getpostevent_ajax_request'); |
Hi vọng sẽ giúp được bạn. Thanks!.