使用AJAX在WordPress中进行MySQL查询

时间:2015-12-14 作者:theo

我有一个搜索表单,它搜索数据库并返回一些数据。我已经设法使用Wordpress wpdb连接并在表上使用select语句并检索数据。一切正常。。但是我有页面刷新问题。我想添加AJAX代码,以便在不刷新数据的情况下获取数据。所以,我一直跟着this, this 和教程。但是,我面临着一些问题。所以,我得到的是:

我的JS代码:

var j$ = jQuery;
var search_text = j$(".cv__text").val();
j$.post({
    url: "<?php echo admin_url(\'admin-ajax.php\'); ?>",
    data: ({
        action: "search_cv", search_text: search_text
    }),
    success: function (response){
        console.log(response);
        j$("#search_results").html(response);
    }
}); 
我的职能。php:

function search_cv(){
    $search_text = ucfirst($_POST["search_text"]);

    //Creating New DB Connection

    $database_name = "employee_cv";

    $mydb = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST);
    $mydb -> show_errors();

    if ($_POST["search_text"] != null){

        $result = $mydb -> get_results(
            $mydb -> prepare(
                \'SELECT * FROM employee 
                WHERE Experience = %s\',
                $search_text
            ) );

    }

    foreach ($result as $employee){
        //Here I just echo html blocks (divs, paragraphs etc.)                          
    }

    die();
}

add_action( \'wp_ajax_search_cv\', \'search_cv\' );
add_action( \'wp_ajax_nopriv_search_cv\', \'search_cv\' );
我的HTML:

<form class="searchCV_form" role="form" action="">
    <div>
        <input type="text" id="search_text" name="search_text" class="cv__text">
        <span class="input-group-btn">
            <button type="submit" class="btn btn-default btn-primary cv__button search--form-btn">SUBMIT</button>
        </span>
    </div>
</form>
<div id="search_results"></div>
所以,在所有这些更改之后,我仍然可以刷新页面,而且我的查询根本不起作用。我不确定我在这里做错了什么。我以前在项目中使用过AJAX,但从未使用过Wordpress和php。

EDIT

显然,要么我做错了什么,要么这个问题错了。有人能告诉我如何使用AJAX和对MySQL的wpdb请求吗?凭自己的经验?最好有一些细节?我找到的所有教程似乎都让我失望。

3 个回复
最合适的回答,由SO网友:jgraup 整理而成

我需要看看你的触发器功能,但听起来你只需要添加event.preventdefaultsubmit. 这将在仍执行AJAX时阻止页面加载。

$("form.searchCV_form").submit(function(event){
    event.preventDefault();

    alert( "We\'re not going anywhere now..." );
    // j$.post...
}); 

$("form.searchCV_form").submit(function(e){
    alert( "We\'re not going anywhere now..." );
    // j$.post...

    return false;
});
更多信息,请访问event.preventDefault() vs. return false.

这里有一些mod可以让它按照您的预期工作——无需实际搜索。

类型

<form class="searchCV_form" role="form" action="">
     <div>
         <input type="text" id="search_text" name="search_text" class="cv__text">
         <span class="input-group-btn">
             <button type="submit" class="btn btn-default btn-primary cv__button search--form-btn">SUBMIT</button>
         </span>
     </div>
 </form>
 <div id="search_results"></div>
JQUERY

<script>
// wrap everything in a closure
(function($){

  // get our references
  var $form = $(\'form.searchCV_form\'),
      $search_field = $(\'#search_text\'),
      $results = $(\'#search_results\');

  // AJAX search call
  function do_search() {

    // grab the query value from the search field
    var search_text = $search_field.val();

    // do a POST ajax call
    $.ajax({
      type: "POST",
      url: \'<?php echo admin_url(\'admin-ajax.php\'); ?>\',
      data: ({
        action: "search_cv",
        search_text: search_text
      }),
      success: function (response){
        console.log(response);
        $results.html(response);
      }
    });
  }

  // on submit, do the search but return false to stop page refresh
  $form.submit(function(e) {
    do_search();
    return false;
  });

})(jQuery);
</script>
WP AJAX

function search_cv()
{
    // get the search query
    $search_text = ucfirst($_POST["search_text"]);

    // clean it up
    $search_text = sanitize_text_field( $search_text);

    // ... do stuff with it

    // output the HTML which will be consumed by $.html()
    ?><div>You searched for <?php echo $search_text; ?> and we found... </div><?php

    // stop doing stuff
    die();
}

add_action( \'wp_ajax_search_cv\', \'search_cv\' );
add_action( \'wp_ajax_nopriv_search_cv\', \'search_cv\' );

SO网友:s_ha_dum

您的Javascript文件中包含PHP:

url: "<?php echo admin_url(\'admin-ajax.php\'); ?>",
PHP解释器不会解析Javascript文件,因此您提供的URL实际上是<?php echo admin_url(\'admin-ajax.php\'); ?>. 您需要创建一个可以访问的Javascript变量。您要做的是(摘自wp_localize_script() codex页面,有修改:

// Register the script
wp_register_script( \'some_handle\', \'path/to/myscript.js\' );

// Localize the script with new data
$translation_array = array(
    \'myajax_url\' => admin_url(\'admin-ajax.php\'),
);
wp_localize_script( \'some_handle\', \'object_name\', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( \'some_handle\' );
然后在Javascript中:

url: some_handle.myajax_url,

SO网友:CiprianD

// Register the script - located in functions.php (usually)
wp_register_script( \'some_handle\', \'path/to/myscript.js\' );

//In the file you need the ajax results

// Enqueued script
wp_enqueue_script( \'some_handle\' );

// Localize the script with new data
wp_localize_script( \'some_handle\', \'object_name\', array(\'ajax_url\' => admin_url( \'admin-ajax.php\' ) );

// the ajax call in the js file
jQuery.ajax({
    url : object_name.ajax_url,
    type : \'post\',
    data : {
           action:\'search_cv\', 
           search_text: search_text
    }
    success : function( response ) {
         response = jQuery.parseJSON(response);
         //use the response variable to print what you need on the webpage. Basically instead of running the foreach in the php function run it here with js
   }
 });
在php函数中(应该在functions.php中),删除foreach并只回显结果

echo json_encode($results);

相关推荐

如果作者没有帖子,则Auth.php不显示内容

我正在制作一个自定义的创世主题,并有一个自定义的作者。php文件,该文件拉入各种自定义字段(使用高级自定义字段),并将作者配置文件页面中的作者元信息添加到页面中。。。它还显示他们的最新帖子。如果作者已经为其分配了帖子,那么这一点非常有效。如果没有,页面将不会输出通常从作者档案中提取的任何内容。。。我搜索了StackExchange,虽然这已经被提到过几次,但我似乎找不到一个有效的答案。我需要作者。php页面输出作者信息,无论用户是否有帖子。如果没有,配置文件元和自定义字段仍应显示,最近的帖子部分不应显示其