将php变量添加到wordpress mysql查询中

时间:2014-08-21 08:43:44

标签: php jquery mysql wordpress

我正在尝试从ajax查询中插入DB数据。当我用简单的文本测试函数时,它可以工作:

array('reference_id'=> 'test'),
array('checkin_time'=> 'test'), 

但我的PHP变量没有正确(由alert()测试,它们都是字符串)

array('reference_id'=> $calendartime),
array('checkin_time'=> $reference_id),

以下是我的模板functions.php中的完整代码:

wp_enqueue_script('jquery');
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php'       ) ) );

function addCheckin(){
   global $wpdb, $calendartime, $reference_id;
   $calendartime = $_POST['calendar_time'];
   $reference_id = $_POST['reference_id'];

   if($wpdb->insert('checkin',
   array('reference_id'=> $calendartime),
   array('checkin_time'=> $reference_id),
   array( '%s'), 
   array( '%s') )===FALSE){

       echo "Error";
   }else {}
   die();
}

add_action('wp_ajax_addCheckin', 'addCheckin');
add_action('wp_ajax_nopriv_addCheckin', 'addCheckin');

jquery

   $.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data:{
              action: addCheckin,
              reference_id: $('.reference input').val(),
              calendar_time: calendar
        },
        success: function(response) {
            alert(response);
        },
        error: function(){
            alert("failure");
        }
   });

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

你的WordPress插件似乎有误。它应该是:

$wpdb->insert('checkin',
array('reference_id' => $calendartime,
'checkin_time' => $reference_id),
array( '%s', '%s') )

我还认为您的AJAX后期JavaScript应该是:

$.post(   MyAjax.ajaxurl,  {
            data:{
              action: addCheckin,
              reference_id: $('.reference input').val(),
              calendar_time: calendar
            },
        success: function(response) {
            alert(response);
        },
        error: function(){
            alert("failure");
        }
   });

答案 1 :(得分:0)

更新:我将以下代码添加到我的主题header.php(这是使用Contact Form 7的页面):

<script type='text/javascript' src='/wp-content/plugins/contact-form-7/includes/js/jquery.form.min.js?ver=3.40.0-2013.08.13'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var _wpcf7 = {"loaderUrl":"\/wp-content\/plugins\/contact-form-7\/images\/ajax-loader.gif","sending":"Sending ..."};
/* ]]> */
</script>
<script type='text/javascript' src='/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=3.5.2'></script>

现在它可以使用以下代码:

var data = {
          'action': 'form',
          'reference_id': $('.reference input').val(),
          'calendar_time': calendar
     };

$.post( form.ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
    });

希望它会有所帮助