1
所以我想在wp中做一個按鈕,並且出於某種原因,ajax按鈕不能正常工作。 這裏有什麼應該發生Ajax按鈕不起作用
- 用戶點擊#followbtn
- 阿賈克斯去$ _ POST的行動,=跟隨
- PHP運行wp_set_object_terms($ USER_ID,$ AUTHOR_ID, '關注' 的步驟,真正的);
- 當這樣做的功能回聲的「OK」
- 如果數據= OK重新加載頁面
出於某種原因,PHP是不執行和頁面沒有被重新加載。
add_action('wp_ajax_nopriv_jk-author-follow', 'jk_author_follow');
add_action('wp_ajax_jk-author-follow', 'jk_author_follow');
function jk_author_follow() {
$nonce = $_POST['nonce'];
if (! wp_verify_nonce($nonce, 'ajax-nonce'))
die ('Nope!');
if($_POST['action'] == "follow") {
$author_id = get_the_author_meta('nickname'); // get authors name
$termId = get_term_by('slug', $author_id, 'follow'); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term($termId, 'follow'); // count followers in author term
$author_follow_count = count($followers);
if (is_user_logged_in()) { // user is logged in
$user_id = get_current_user_id(); // current user
wp_set_object_terms($user_id, $author_id, 'follow', true); // Follow the author
echo "ok";
}
}
}
exit;
}
前端按鈕
function getAuthorFollowLink($author_id) {
$author = get_the_author_meta('nickname');
$user_ID = get_current_user_id();
$termId = get_term_by('slug', $author, 'follow'); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term($termId, 'follow'); // count followers in author term
$count = count($followers);
$output = '<a href="#" id="followbtn">Folllow '.$count.'</a>';
return $output;
}
JS
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: ajax_var.url,
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
location.reload();
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
有沒有這樣的事情作爲ajax按鈕 – beauXjames