Hướng dẫn wordpress ajax on button click - wordpress ajax khi nhấp vào nút

CẬP NHẬT: Tôi đã quản lý để có được AJAX hoạt động, nhưng không phải trong sự kiện nhấp chuột. Tôi đã cập nhật câu hỏi để phù hợp với điều này. I managed to get the AJAX working, but not in the click event. I updated the question to match this.

Tôi đang thử một số mã tôi tìm thấy trên trang: 'Ajax trong các plugin'.

Tuy nhiên tôi không thể làm cho nó hoạt động và tôi thực sự không biết bắt đầu tìm kiếm ở đâu. Nó hoạt động khi tôi xóa chức năng nhấp chuột và chỉ chạy mã trên Pageload.

Tôi có một tệp JavaScript trông giống như điều này:

jQuery(document).ready(function(){
    jQuery("#createremotesafe").click(function(){
        alert ('test');
        var data = {
            action: 'my_action',
            whatever: 1234
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php

        jQuery.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });    
});

và ở đâu đó trong tập lệnh PHP của tôi tạo nút sẽ thực thi JavaScript (tức là trang quản trị viên) và cả phần còn lại của trang:

add_action('wp_ajax_my_action', 'my_action_callback');
echo 'test2';
function my_action_callback() {
  global $wpdb; // this is how you get access to the database
  $whatever = $_POST['whatever'];
  $whatever += 10;
  echo $whatever;
  die(); // this is required to return a proper result
}

Tôi nhận được cả Alert ('test')echo 'test2', nhưng không phải là cảnh báo phản hồi. Không có lỗi JavaScript hoặc bất cứ điều gì. Mã của tôi chắc chắn đang chạy, vì tôi có thể thấy cả hai bài kiểm tra, nhưng tại sao Ajax không nhận được phản hồi nào? Chức năng PHP của tôi có biến mất sau khi tải trang không? Có lẽ tôi không thể/không nên sử dụng các hàm WP AJAX tích hợp?

Nó cũng không hiển thị một hộp cảnh báo trống, không có gì xảy ra.

Tôi đang cố gắng lấy dữ liệu từ chức năng PHP trong một plugin WordPress bằng AJAX. Tôi cần nói thêm rằng các móc này hoàn toàn khó hiểu với tôi ... Tôi đang chơi xung quanh với ví dụ từ https://codex.wordpress.org/ajax_in_plugins và tôi đã thay đổi một chút để cảnh báo một số dữ liệu khi nhấp vào nút.

Trong plugin của tôi:

    function my_enqueue($hook) {
                /**if( 'index.php' != $hook ) {
                // Only applies to dashboard panel
                return;
                }*/


                wp_enqueue_script( 'ajax-script', plugins_url( 'js/formAdd_.js', __FILE__ ), array('jquery') );

                // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
            wp_localize_script( 'ajax-script', 'ajax_object',
                    array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ); );
            }
            add_action( 'wp_enqueue_scripts', 'my_enqueue' );

            // Same handler function...
            add_action( 'wp_ajax_my_action', 'my_action_callback' );
            add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
            function my_action_callback() {
                global $wpdb;

                $names = array();
                            while ( bp_group_members() ) : bp_group_the_member();


                                array_push($names, bp_group_member_name() );

                            endwhile;
                    echo json_encode($names);
                die();
            }

Và trong tệp JS của tôi:

jQuery(document).ready(function($) {

//ajax example
jQuery('.ajaxTrigger').live('click',function(){  
var data = {
        'action': 'my_action',
        'whatever': ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
    jQuery.post(ajax_object.ajax_url, function(response) {
        alert(response[0]);
    });
});

Và nút ở đâu đó trong plugin của tôi:


Tôi không chắc điều gì sai ở đó, về mặt kỹ thuật tôi sẽ có thể gọi chức năng chỉ bằng một cú nhấp chuột đơn giản hoặc chức năng PHP được cho là được kích hoạt trước?

Ngoài ra lỗi trong bảng điều khiển cho biết bài WP-admin/admin-ajax.php 500 (lỗi máy chủ nội bộ)

Update:

Đã loại bỏ một số mã không cần thiết khỏi JavaScript và cảnh báo là ở đó tuy nhiên nó chỉ cảnh báo 0, vì vậy điều đó có nghĩa là vòng lặp trong khi chức năng PHP của tôi không trả về một mảng thích hợp mà tôi nghĩ.

jQuery('.ajaxTrigger').live('click',function(){  

    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
    jQuery.post(ajax_object.ajax_url, function(response) {
        alert(response[0]);
    });
});

Toàn bộ mã plugin PHP

function my_plugin_init() {
    require_once( dirname( __FILE__ ) . '/getGroupExt.php' );

/* If you have code that does not need BuddyPress to run, then add it here. */

if ( !defined( 'ABSPATH' ) ) exit;

                wp_enqueue_script( 'ajax-script', plugins_url( 'js/formAdd_.js', __FILE__ ), array('jquery') );

                // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
                wp_localize_script( 'ajax-script', 'ajax_object',
                        array( 'ajax_url' => admin_url( 'admin-ajax.php' )) );
            }
            add_action( 'wp_enqueue_scripts', 'my_enqueue' );

            // Same handler function...
            add_action( 'wp_ajax_my_action', 'my_action_callback' );
            add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
            function my_enqueue($hook) {
                /**if( 'index.php' != $hook ) {
                // Only applies to dashboard panel
                return;
                }*/
                        function my_action_callback() {
                global $wpdb;

                $names = array();
                if ( bp_group_has_members( 'group_id='.bp_get_group_id().'&exclude_admins_mods=false' ) ) : 

                while ( bp_group_members() ) : bp_group_the_member();


                             //$name = bp_get_group_member_name();             
                                $name = bp_group_member_name() ;

                                array_push($names, $name);

                            endwhile;
                    echo json_encode($names);
                die();
                endif;
            }

/**
 * The class_exists() check is recommended, to prevent problems during upgrade
 * or when the Groups component is disabled
 */
if ( class_exists( 'BP_Group_Extension' ) ) :

class Group_Extension_Example_1 extends BP_Group_Extension {
    /**
     * Your __construct() method will contain configuration options for 
     * your extension, and will pass them to parent::init()
     */
    function __construct() {
        $args = array(
            'slug' => 'group-extension-example-1',
            'name' => 'Group Extension Example 1',
        );
        parent::init( $args );
    }

 //from ajax example



    /**
     * display() contains the markup that will be displayed on the main 
     * plugin tab
     */
    function display() {
        //if admin
        $user_id=get_current_user_id();
        $group_id = bp_get_group_id();
        if (groups_is_user_admin( $user_id, $group_id )) {
            echo 'There are no tasks! - Set your tasks for this group';
            ?>
            

you're not part of any groups.


Save your plugin setting here:

Cảm ơn trước.

Tôi có thể sử dụng Ajax trong WordPress không?

Bạn có thể thấy Quản trị viên của Quản trị viên. Nó ban đầu được tạo ra cho tất cả các chức năng thực hiện các yêu cầu AJAX từ Quản trị viên WordPress. Nó cũng được sử dụng cho phần công khai của web. Tất cả các yêu cầu AJAX WordPress phải đi qua tập lệnh PHP. Nói cách khác, quản trị viên-Ajax.All WordPress AJAX requests must go through a PHP script. In other words, admin-ajax.

Làm cách nào để tải nhiều bài viết hơn trên Ajax Nhấp vào WordPress?

Tải thêm bài viết với Ajax trong WordPress, không tải lại trang ...
Thiết lập truy vấn WordPress cơ bản ..
Tạo chức năng AJAX để tải nhiều bài viết hơn ..
Tạo tải WordPress nhiều truy vấn hơn ..
Kết hợp Ajax và WordPress ..
Ẩn tải thêm nút (khi không có thêm bài viết).
WordPress Partination với Offset ..

Làm thế nào tôi có thể biết nếu WordPress Ajax đang hoạt động?

Để xem nếu yêu cầu hiện tại là yêu cầu AJAX được gửi từ thư viện JS (như jQuery), bạn có thể thử một cái gì đó như thế này: if (!) == 'xmlhttprequest') {// Đây là một yêu cầu ajax.}if( ! empty( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) == 'xmlhttprequest' ) { //This is an ajax request. }

Làm cách nào để nhận dữ liệu AJAX trong WordPress?

Sử dụng Ajax trong WordPress..
add_action ('wp_enqueue_scripts', 'my_enqueue') ;.
hàm my_enqueue () {.
wp_enqueue_script ('like_post', get_template_directory_uri (). '/ js/ post-like.js', '1.0', 1) ;.
wp_locize_script ('like_post', 'ajax_var', mảng (.
'url' => admin_url ('admin-ajax.php'),.
'nonce' => wp_create_nonce ('ajaxnonce').