即使使用die()并更正wp_ajax_ACTION,Wordpress Ajax调用($ .post)也会返回0- [英] Wordpress Ajax call ($.post) returns 0 - even when using die() and correct wp_ajax_ACTION

查看:82
本文介绍了即使使用die()并更正wp_ajax_ACTION,Wordpress Ajax调用($ .post)也会返回0-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在站点的子域上构建wordpress插件(我只提到它是因为我不认为这是xss问题).我正在将Ajax与Jquery一起用于管理端(后端,而不是前端)上的功能;在管理面板上.

Building a wordpress plugin on Subdomain of site (I only mention it because I don't think this is an xss issue). Am using Ajax with Jquery for functionality on Administrative Side (Backend, not Frontend); on admin panels.

但是,Ajax继续返回0;尽管我在调用/处理函数的末尾具有"die()",并且使用了正确的Ajax"Action"调用(wp_ajax_ACTION).完整代码如下.希望您能提供帮助.

However, Ajax keeps returning 0; this is in spite of me having 'die()' at end of the calling/handler function and using the correct Ajax 'Action' call (wp_ajax_ACTION). Full code below. Hope you can help.

JQUERY ...("t-admin.js"):

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

 $('#p2_form1').submit(function() {
var data = {
    action: "results_test"
};
try {
$.post(ajaxurl, data, function(response) {
    // jQuery('#ajax_data').html(response);
     alert ('Response is: ' + response);
    // this call should return "DATA TO BE ECHOED!"
    // alert (typeof response); // this returns 'string'; don't know why
    });
} catch (err) {
    return err;
}

    return false;
 });
});

PHP调用/处理程序文件(管理面板第2页)...('t-page2.php'):

<?php
// protect page; make sure user can update opts
if ( !current_user_can('manage_options') ) {
    wp_die (__("You don't have permission to access this page.") );
}
?>

<div class="wrap">
  <?php screen_icon('options-general'); ?>
    <h2>
      <?php _e('Manage Page 2 Settings:'); ?>
    </h2>
    <p>Settings form here...
        <form name="p2_form1" id="p2_form1" method="post" action="">
          <?php settings_fields('tp2_opts_groups'); ?>
         <p>input fields, radio buttons, blah blah</p>
          <input type="submit" id="test_submit" value="Test Submit Button" class="button-primary" />
         </form>

          <?php
          // error_reporting(E_ALL);
          // TESTING AJAX RESUTLS...
            function my_action_callback() {
                 echo ("DATA TO BE ECHOED!");
                die(); 
              }
          // Keep getting 0. Why? Am using "die()" at end and wp_ajax_ACTION is correct.

          add_action( 'wp_ajax_results_test', 'my_action_callback');
          // add_action( 'wp_ajax_nopriv_results_test', 'my_action_callback');
          // NoPriv not necessary. This is on Admin Panels (Backend, NOT Frontend)
          ?>
          <p> data will appear here...</p>
          <div id="ajax_data">
          <!-- data to eventually appear here! -->
          </div>


</div>

如果有人需要查看整个代码,则可以保留文件的其余部分...

插件文件...('test-plugin.php'):

<?php
defined( 'ABSPATH' ) OR exit;
/*
Plugin Name: Test Plugin
Version: 1.0
Author: WP Plugin Newbie
Description: Building my first plugin.
Version: 1.0
License: Free
*/

// protect page
if ( !function_exists('add_action') ) {
    echo ( "Sorry, this page doesn't do much when accessed directly" );
    exit(0);
}


// main class to handle function calls
class TestPluginCls {
    public $version_num = '1.0';

    function TestPluginCls() {
        // get constants
        $this->TestPluginConstants();
        // register db setup
        register_activation_hook( __FILE__, array(&$this, 'setup_DB') );
        // action
        add_action( 'plugins_loaded', array(&$this, 'start_TestPlugin') );
    }

    // set up db
    function setup_DB() { 
        // require
        require_once ( dirname(__FILE__) . '/admin/t-dbsetup.php' );
        // call db class
        $this->TestPluginDbSetupCls = new TestPluginDbSetupCls();
    } 

    // launch Test Plugin
    function start_TestPlugin() {
        if ( is_admin() ) {
            // require
            require_once ( dirname(__FILE__) . '/admin/t-admin.php' );
            // setup Admin area
            $this->TestPluginAdminAreaCls = new TestPluginAdminAreaCls();
        } 

    }

    // define constants
    function TestPluginConstants() {
        define ( 'TestPlugin_FOLDER', plugin_basename(dirname(__FILE__)) );
        define ( 'TestPlugin_URL', plugin_dir_url(__FILE__) );
        define ( 'TestPlugin_PATH', plugin_dir_path(__FILE__) );
    }

}

global $TestPlugin;
global $wpdb;
$TestPlugin = new TestPluginCls();

?>

管理员/菜单构建类...('t-admin.php'):

<?php

 error_reporting(E_ALL);
// ini_set('display_errors', '1');

class TestPluginAdminAreaCls {
    public $role = 'activate_plugins';

    function TestPluginAdminAreaCls() {
        // register stuff
        add_action( 'admin_menu', array(&$this, 'TestPluginMenu') );
        add_action( 'admin_init', array(&$this, 'register_tplugin_options') );
        // add_action( 'wp_ajax_get_tmps', 'my_action_cb'); // placing here produces error notice!
        // add_action( 'admin_enqueue_scripts', array(&$this, 'tp_load_admin_scripts') );

    }

    // build menu
    function TestPluginMenu() {

        $phsfx_home = add_menu_page( __('Test Plugin Admin Area'), __('Test Plugin'), $this->role, TestPlugin_FOLDER, array(&$this, 'output_page') );

        $phsfx_main = add_submenu_page( TestPlugin_FOLDER, __('Test Plugin Admin Area'), __('TP Main'), $this->role, TestPlugin_FOLDER, array(&$this, 'output_page') );

        $phsfx_p1 = add_submenu_page( TestPlugin_FOLDER, __('Test Plugin : Page 1'), __('TP Page 1'), $this->role, 'tp1', array(&$this, 'output_page') );

        $phsfx_p2 = add_submenu_page( TestPlugin_FOLDER, __('Test Plugin: Page 2'), __('TP Page 2'), $this->role, 'tp2', array(&$this, 'output_page') );


    // only show admin scripts and dependencies on TP pages as needed
        add_action( 'admin_print_scripts-' . $phsfx_home, array(&$this, 'tp_load_admin_scripts') );
        add_action( 'admin_print_scripts-' . $phsfx_main, array(&$this, 'tp_load_admin_scripts') );
        add_action( 'admin_print_scripts-' . $phsfx_p1, array(&$this, 'tp_load_admin_scripts') );
        add_action( 'admin_print_scripts-' . $phsfx_p2, array(&$this, 'tp_load_admin_scripts') );

    }

    function register_tplugin_options() {
        // add_action( 'wp_ajax_get_tmps', 'my_action_cb'); // placing here throws crazy error notice!
        register_setting( 'tp1_opts_groups', 'tp1_opts' );
        register_setting( 'tp2_opts_groups', 'tp2_opts');
    }

    // output proper page
    function output_page() {
        switch ($_GET['page']) {
            case "tp1" :
                include_once( dirname(__FILE__) . '/t-page1.php');
                break;
            case "tp2" :
                include_once( dirname(__FILE__) . '/t-page2.php');
                break;
            default :
                include_once( dirname(__FILE__) . '/t-main.php');
                break;
        }
    }

    // scripts/css
    function tp_load_admin_scripts() {
    // load JS
        wp_enqueue_script ( array('jquery', 'farbtastic', 'media-upload', 'postbox', 'thickbox') );
        wp_enqueue_script ( 't-admin-js', TestPlugin_URL.'js/t-admin.js', array('jquery'), '1.0' );
    // localize???
        //wp_localize_script ( 't-admin-js', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); // don't know if necessary

    // load CSS
        wp_enqueue_style ( array('thickbox', 'farbtastic') );
        wp_enqueue_style ( 't-admin-css', TestPlugin_URL.'css/t-admin.css', array(), '1.0', 'screen' );

    }

}


?>

数据库设置类...('t-dbsetup.php'):

<?php

class TestPluginDbSetupCls {

    function TestPluginDbSetupCls() {
        global $wpdb;

        // insert info into DB...
        // Tested. All code here works.
    }

}
?>

管理面板主页...('t-main.php'):

<?php
// protect page
if ( !current_user_can('manage_options') ) {
    wp_die (__("You don't have permission to access this page.") );
}
?>

<div class="wrap">
    <h2>Test Plugin</h2>
  <p><b>Manage Page 1:</b></p>
    <blockquote class="section">
      <p><a href="#">Link to page 1 settings</a> -- Here is where you can...</p>
  </blockquote>

    <p><b>Manage Page 2:</b></p>
    <blockquote class="section">
      <p><a href="#">Link to page 2 settings</a> -- Here is where you can...</p>
  </blockquote>

</div>

管理面板第1页...('t-page1.php'):

<?php
// protect page; make sure user can update opts
if ( !current_user_can('manage_options') ) {
    wp_die (__("You don't have permission to access this page.") );
}
?>

<div class="wrap">
  <?php screen_icon('options-general'); ?>
    <h2>
      <?php _e('Manage Page 1 Settings:'); ?>
    </h2>
    <p>Settings form here...</p>
          <form name="p1_form1" id="p1_form1" method="post" action="">
          <?php settings_fields('tp1_opts_groups'); ?>
          <p>input fields, radio buttons, blah blah</p>
          <p>&nbsp;</p>
          </form>
</div>

推荐答案

未注册Ajax调用.必须将处理程序功能 my_action_callback()从文件't-page2.php'移到 TestPluginMenu()内部函数,位于菜单构建类 TestPluginAdminAreaCls 中-都在文件't-admin.php'中.

Ajax call was not being registered. Had to move the handler function, my_action_callback(), from the file, 't-page2.php', to inside the TestPluginMenu() function, located inside the menu-building class, TestPluginAdminAreaCls -- both in file, 't-admin.php'.

还必须将"add_action(wp_ajax_ ..." )移到类函数 TestPluginAdminAreaCls 之外.

Also had to move the "add_action (wp_ajax_ ..." to outside of the class function, TestPluginAdminAreaCls.

课程:首先确保您的ajax处理程序已正确注册.

The lesson: Make sure your ajax handlers are being registered properly in the first place.

这篇关于即使使用die()并更正wp_ajax_ACTION,Wordpress Ajax调用($ .post)也会返回0-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆