【问题标题】:Calling AJAX function on button click within WordPress plugin在 WordPress 插件中单击按钮时调用 AJAX 函数
【发布时间】:2015-02-03 22:55:39
【问题描述】:

我正在尝试使用 AJAX 从 WordPress 插件中的 php 函数获取数据。我需要补充一点,这些钩子让我完全困惑......我正在玩https://codex.wordpress.org/AJAX_in_Plugins 的示例,我对其进行了一些更改,以在单击按钮时提醒一些数据。

在我的插件中:

    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();
            }

在我的 js 文件中:

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]);
    });
});

还有我插件中某处的按钮:

<button type="button" class="ajaxTrigger">Click Me!</button>

我不确定那里出了什么问题,从技术上讲,我应该能够通过简单的按钮单击来调用该函数,还是应该首先触发 php 函数?

控制台中的错误也显示 POST wp-admin/admin-ajax.php 500 (Internal Server Error)

更新:

从 JavaScript 中删除了一些不必要的代码,并且警报在那里但是它只是警报 0,所以这意味着我的 php 函数中的 while 循环没有返回我认为的正确数组。

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]);
    });
});

整个插件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';
            ?>
            <div class="input_fields_wrap">
            <button class="add_field_button">Add Another Task</button>
            <p><input type="text" name="mytext[]"></p>
            <button type="button" class="ajaxTrigger">Click Me!</button>

            <?php   
                $has_members_str = "group_id=" . $group_id;
                if ( bp_group_has_members( $has_members_str ) )
                : ?>
                <select name ="member">
                <?php while ( bp_group_members() ) : bp_group_the_member(); ?>

                    <option value="<?php bp_group_member_name() ?>"> <?php bp_group_member_name() ?> </option>

                <?php endwhile; ?>
                </select>
                <?php else: ?>
                <h2>you're not part of any groups.</h2>
                <?php endif;?>
                <input id="enddate" name="enddate" min="2014-12-01" max="2019-01-01" type="date">
        </div> <br />


            <?php

        }
        else {
            echo "You're not an admin!";
        }
    }

    /**
     * settings_screen() is the catch-all method for displaying the content 
     * of the edit, create, and Dashboard admin panels
     */
    function settings_screen( $group_id ) {
        $setting = groups_get_groupmeta( $group_id, 'group_extension_example_1_setting' );

        ?>
        Save your plugin setting here: <input type="text" name="group_extension_example_1_setting" value="<?php echo esc_attr( $setting ) ?>" />
        <?php
    }

    /**
     * settings_sceren_save() contains the catch-all logic for saving 
     * settings from the edit, create, and Dashboard admin panels
     */
    function settings_screen_save( $group_id ) {
        $setting = '';

        if ( isset( $_POST['group_extension_example_1_setting'] ) ) {
            $setting = $_POST['group_extension_example_1_setting'];
        }

        groups_update_groupmeta( $group_id, 'group_extension_example_1_setting', $setting );
    }
}
bp_register_group_extension( 'Group_Extension_Example_1' );

endif; // if ( class_exists( 'BP_Group_Extension' ) )

}
add_action( 'bp_include', 'my_plugin_init' );

?>

提前致谢。

【问题讨论】:

  • 不,我只是在此处粘贴了一段脚本。不包括在内是什么意思?在我的插件中? wp_enqueue_script('ajax-script', plugins_url('js/formAdd_.js', FILE), array('jquery'));那不应该包括它吗?
  • 是的,这基本上就是我发布的链接中的示例。我刚刚更改了它,因此它不仅适用于后端的管理员。我做错的一件事是通过 AJAX 将变量传递给 php,而在这里我只需要一个响应,但在控制台中仍然出现错误。我要更新我的代码。

标签: php ajax wordpress


【解决方案1】:

如果您想使用ajax_object.we_value,则必须使用wp_localize_script() 创建该变量:

add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue()
{
    wp_enqueue_script( 'ajax-script', plugins_url( 'js/formAdd_.js', __FILE__ ), array( 'jquery' ) );

    wp_localize_script( 'ajax-script', 'ajax_object', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'we_value' => 'test'
    ) );
}

在您的 JS 中,使用 ajax_object.we_value 并将其作为 whatever 发布到 admin-ajax.php

jQuery(document).ready(function($) {
    $('body').on('click', '.ajaxTrigger', function(){
        $.ajax({
            type: 'POST'
            ,dataType: 'json'
            ,url: ajax_object.ajax_url
            ,data: {
                'action': 'my_action',
                'whatever': ajax_object.we_value
            }
            ,success: function(response) {
                alert(response);
            }
        });
    });
});

在您的 AJAX 回调中,捕获并使用 whatever 值,然后发回响应:

add_action( 'wp_ajax_my_action',        'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
    $names = array( $_POST['whatever'] . ' successful!' );

    echo json_encode( $names );

    exit;
}

【讨论】:

  • 嘿,谢谢你的回复,但我不需要通过 AJAX 将变量传递给 php,所以我更新了我的代码,但警报显示 '0' 而不是名称,我认为这是因为循环使用 buddypress 函数,但所有内容都放在 if (class_exists('BP_Group_Extension')) 之前:?但是当我把它放在那里时,我无法加载 wordpress,所以我不知道如何解决它。我会在一分钟内用整个代码更新我的帖子。
  • 我对 BP 不是很熟悉,但我猜像 bp_get_group_id() 这样的函数不会在 admin / AJAX 上下文中返回正确的值。因此,我认为您必须使用 wp_localize_script() 和 JS 中的数据选项将这些值传递给 AJAX 回调。
猜你喜欢
  • 2012-01-25
  • 1970-01-01
  • 2017-04-21
  • 2017-11-24
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多