こちらにあげたコードの、js/script.js
内でajax通信をするのですが、
返り値末尾に0がついてしまい困っています。
呼んでいる関数は、get-hearts.php
内のghe_give_heart
です。
どなたかわかる方、お願いいたします。。
php
1function get_heart_everyday() { 2 $post_id = get_the_ID(); 3 if(!get_post_meta($post_id, 'ghe_count', true)) { 4 add_ghe_fields($post_id); 5 } 6 7 echo ' 8 <div class="ghe-container"> 9 <div class="ghe-trigger" data-id="'.$post_id.'"> 10 <img src="' . plugins_url('get-hearts/images/inactive.svg') . '" alt="" class="ghe-image"> 11 </div> 12 <div class="ghe-count">'.get_post_meta($post_id, 'ghe_count', true).'</div> 13 </div> 14 '; 15} 16 17add_action( 'wp_ajax_ghe_give_heart', 'ghe_give_heart' ); 18add_action( 'wp_ajax_nopriv_ghe_give_heart', 'ghe_give_heart' ); 19function ghe_give_heart() { 20 $post_id = intval($_REQUEST['postId']); 21 $new_count = get_post_meta($post_id, 'ghe_count', true) + 1; 22 update_post_meta($post_id, 'ghe_count', $new_count); 23 24 $data = array( 25 'count' => get_post_meta($post_id, 'ghe_count', true) 26 ); 27 echo json_encode($data); 28} 29 30add_action('publish_post', 'add_ghe_fields'); 31add_action('publish_page', 'add_ghe_fields'); 32function add_ghe_fields($post_ID) { 33 if(!wp_is_post_revision($post_ID)) { 34 add_post_meta($post_ID, 'ghe_count', 0, true); 35 } 36}
js
1$(function() { 2 const $trigger = $('.ghe-trigger'); 3 $trigger.on('click', function() { 4 let $el = $(this); 5 let $image = $el.find('.ghe-image'); 6 let $count = $el.siblings('.ghe-count'); 7 8 let postId = $el.data('id'); 9 10 $.ajax({ 11 type: 'POST', 12 xhrFields: { withCredentials: true }, 13 dataType: 'text', 14 url: ajax_url, 15 cache: false, 16 data: { 17 action: 'ghe_give_heart', 18 postId: postId 19 } 20 }).then( 21 function(data) { 22 $image.attr('src', image_root_path + 'active.svg'); 23 $count.text(data); 24 }, 25 function() { 26 console.log('ajax error'); 27 } 28 ); 29 }) 30})
ちなみにコード全体は、Githubこちらにあげています。
回答2件
あなたの回答
tips
プレビュー