wordpress ajax不更新数据库

时间:2014-12-04 05:09:15

标签: php ajax wordpress insert

希望你能指导我,我正在尝试运行本教程: http://www.inkthemes.com/how-to-use-ajax-in-wordpress-for-data-insertion/#

这是我的Wordpress插件Javascript:

jQuery(document).ready(function(){
    jQuery("#submit").click(function(){
        console.log("click caught");//this bit works
        var name = jQuery("#dname").val();
        jQuery.ajax({
            type: 'POST',   
            data: {"action": "post_word_count", "dname":name},
            success: function(data){ 
                alert(data);//this alert appears full of html
            }
        });
    });
});

这是插件php:

function show_form(){

echo "<form>";
echo "<label>Name</label>";
echo "<input type='text' id='dname' name='dname' value=''/><br/>";
echo "<input type='button' id='submit' name='submit' value='Submit'/>";
echo "</form>";
}
add_action('the_content', 'show_form');



function post_word_count(){

$name = $_POST['dname'];
global $wpdb;
$wpdb->insert(
    'bio',
    array(
        'bio_surname' => $name
    ),
    array(
        '%s'
    )
);

die();
return true;
}
//
add_action('wp_ajax_post_word_count', 'post_word_count'); // Call when user logged in
add_action('wp_ajax_nopriv_post_word_count', 'post_word_count'); // Call when user in not logged in
?>

所以,我在调试器中发现的是控制台POST数据是&#39; dname&#39;以表格输入提交。但是,数据库表&#34; bio&#34;没有更新。所有这一切都是警报弹出了我正在努力的网站的所有html。即。控制台调试器中的RESPONSE是一个庞大的HTML文本。

所以,我不明白为什么数据=我的网站HTML和为什么表&#34;生物&#34;没有更新。

2 个答案:

答案 0 :(得分:0)

在插件php文件中首先添加你的java脚本文件

wp_enqueue_script('ajax-script-xyz','***javascript file path***', array('jquery')); 
wp_localize_script('ajax-script-xyz', 'ajax_object',
                        array(
                            'ajax_url' => admin_url('admin-ajax.php'),
                            )
                        );

插件Javascript:添加admin-ajax.php文件网址

jQuery(document).ready(function(){
    jQuery("#submit").click(function(){
        console.log("click caught");//this bit works
        var name = jQuery("#dname").val();
        jQuery.ajax(ajax_object.ajax_url, {//**add admin-ajax.php fill url **
            type: 'POST',   
            data: {"action": "post_word_count", "dname":name},
            success: function(data){ 
                alert(data);//this alert appears full of html
            }
        });
    });
});

对于站立的击球手,请检查此链接http://codex.wordpress.org/AJAX_in_Plugins

答案 1 :(得分:0)

您尚未在ajax中定义网址:

jQuery(document).ready(function(){
    jQuery("#submit").click(function(){
        var name = jQuery("#dname").val();
        jQuery.ajax({
            type: 'POST',   // Adding Post method
             url: ajaxurl, // Including ajax file
             data: {"action": "post_word_count", "dname":name}, // Sending data dname to post_word_count function.
             success: function(data){ // Show returned data using the function.
                 alert(data);
        });
    });
});
相关问题