Ajax按钮无法正常工作

时间:2015-04-15 20:29:06

标签: php ajax

所以我试图在wp中创建一个关注按钮,由于某种原因,ajax按钮无法正常工作。 以下是应该发生的步骤

  1. 用户点击#followbtn
  2. Ajax转到$ _POST操作=关注
  3. php运行wp_set_object_terms($ user_id,$ author_id,'follow',true);
  4. 当完成函数echo的“ok”
  5. 如果data = ok重新加载页面
  6. 由于某种原因,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&nbsp;'.$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
     });
    });
    

1 个答案:

答案 0 :(得分:0)

尝试停用此代码

if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
    die ( 'Nope!' );

如果你知道其含义。您可能想了解更多https://codex.wordpress.org/Function_Reference/wp_verify_nonce