douliu1092 2013-11-10 07:57
浏览 68
已采纳

AJAX从Wordpress插件调用的脚本没有得到$ wpdb

I'm writing a Wordpress plugin and want to use ajax to submit data. When using ajax to submit a form in the admin panel, I get this error:

Fatal error: Call to a member function insert() on a non-object in /home1/crave/public_html/wp-content/plugins/MiniCMS/add_contenttype.php on line 13

Here's the script being called. Error line is annotated.

<?php
global $wpdb;

$name = $_POST["name"];
$id = '1';
$text_inputs = $_POST["text_inputs"];
$paragraph_inputs = $_POST["paragraph_inputs"];
$map_inputs = $_POST["map_inputs"];
$file_inputs = $_POST["file_inputs"];

$contentTypeTable = $wpdb->prefix . "minicms_content_type";

//This is line 13, the problem child:
$wpdb->insert( $contentTypeTable, array(
    'name' => $name,
    'id' => $id,
    'text_inputs' => $text_inputs,
    'paragraph_inputs' => $paragraph_inputs,
    'map_inputs' => $map_inputs,
    'file_inputs' => $file_inputs
));
?>

Does anyone know why I'm not getting $wpdb to work?

  • 写回答

1条回答 默认 最新

  • drnvcm3949 2013-11-10 08:11
    关注

    You need to use ajax in WordPress way.

    From WordPress Doc:

    First add some javascript that will trigger the AJAX request:

    <?php
    add_action( 'admin_footer', 'my_action_javascript' );
    
    function my_action_javascript() {
    ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
    
        var data = {
            action: 'my_action',
            whatever: 1234
        };
    
        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        $.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
    </script>
    <?php
    }
    

    Then, set up a PHP function that will handle that request:

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

    Reference:
    1. http://codex.wordpress.org/AJAX_in_Plugins
    2. http://wp.tutsplus.com/articles/getting-started-with-ajax-wordpress-pagination/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭