简体   繁体   English

AJAX从Wordpress插件调用的脚本未获取$ wpdb

[英]Script called by AJAX from Wordpress plugin isn't getting $wpdb

I'm writing a Wordpress plugin and want to use ajax to submit data. 我正在写一个Wordpress插件,想用ajax提交数据。 When using ajax to submit a form in the admin panel, I get this error: 当使用ajax在管理面板中提交表单时,出现此错误:

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 致命错误:在第13行的/home1/crave/public_html/wp-content/plugins/MiniCMS/add_contenttype.php中的非对象上调用成员函数insert()

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? 有谁知道为什么我没有让$ wpdb工作?

You need to use ajax in WordPress way. 您需要以WordPress方式使用Ajax。

From WordPress Doc: 从WordPress Doc:

First add some javascript that will trigger the AJAX request: 首先添加一些将触发AJAX请求的JavaScript:

<?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: 然后,设置一个PHP函数来处理该请求:

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 1. http://codex.wordpress.org/AJAX_in_Plugins
2. http://wp.tutsplus.com/articles/getting-started-with-ajax-wordpress-pagination/ 2. http://wp.tutsplus.com/articles/getting-started-with-ajax-wordpress-pagination/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM