2014-12-04 150 views
1

希望你能指导我,我试图运行此教程: http://www.inkthemes.com/how-to-use-ajax-in-wordpress-for-data-insertion/#WordPress的AJAX没有更新数据库

这是我的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数据是在表单输入中提交的'dname'。但是,数据库表“bio”未被更新。发生的所有事情都是弹出的警报,它包含了我正在使用的所有网站的HTML。即。控制台调试器中的RESPONSE是一个巨大的HTML文本。

所以,我不明白为什么data =我的网站的HTML和为什么表“生物”没有更新。

在插件php文件

回答

0

首先添加您的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:添加管理员-ajax.php文件URL

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

+0

谢谢!现在精美地工作:) – 2014-12-04 05:50:03

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