簡體   English   中英

AJAX從Wordpress插件調用的腳本未獲取$ wpdb

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

我正在寫一個Wordpress插件,想用ajax提交數據。 當使用ajax在管理面板中提交表單時,出現此錯誤:

致命錯誤:在第13行的/home1/crave/public_html/wp-content/plugins/MiniCMS/add_contenttype.php中的非對象上調用成員函數insert()

這是被調用的腳本。 錯誤行已注釋。

<?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
));
?>

有誰知道為什么我沒有讓$ wpdb工作?

您需要以WordPress方式使用Ajax。

從WordPress Doc:

首先添加一些將觸發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
}

然后,設置一個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
}

參考:
1. http://codex.wordpress.org/AJAX_in_Plugins
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