使用ajax的wordpress搜索查询

时间:2015-02-21 17:05:51

标签: jquery ajax wordpress wpdb

我在wordpress中运行wpdb select查询并从文本框中获取它的参数。按下搜索按钮后,结果显示。但我想在没有刷新页面的情况下对ajax做同样的事情。我已尝试过所有内容,但页面仍然刷新。

以下是我的代码

// Jquery代码

jQuery(document).ready(function() {  

   jQuery("#Submityourskill").click(function(){


   jQuery.post(yes.ajaxurl,{action : 'doit'},

    function( response) {//start of funciton


      // alert(response);
       //jQuery("#searchtextbox").val(response);
       jQuery("#result").append(response);
       jQuery("#textarea").html(response);
       return false;
    });//end of function


   }); // click button function finishing here


}); //end of main loop 

HTML

<form action="" method="post">
<div><input maxlength="200" name="secretcode" size="200" type="text" value="" placeholder="Type Here !" />
<input id="Submityourskill" name="Submit" type="submit" value="Search Record" /></div>
</form>
<div id="result"></div>

// php function

function doit() {
if(isset($_POST['secretcode'])!= ''){
if($_POST['Submit']) {

$secretcode=$_POST['secretcode'];
global $wpdb;

$sql = "SELECT * FROM wp_store_locator WHERE sl_description='$secretcode'";
$results = $wpdb->get_results($sql) or die(mysql_error());
 foreach( $results as $result ) {

  echo $result->sl_description;

    }
 exit();
}
  }

以下是我用过的其他php代码

php code

add_action( 'wp_ajax_nopriv_doit', 'doit');
add_action( 'wp_ajax_doit', 'doit' );

以下是将jquery页面排入队列的代码

function add_myjavascript(){  
wp_register_script( 'globals', get_stylesheet_directory_uri() . "/js/ajax-implementationn.js", array( 'jquery' ) ); 
wp_enqueue_script( 'globals' );

// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'globals', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

}  

add_action( 'init', 'add_myjavascript' )

谢谢大家并尊重......!

1 个答案:

答案 0 :(得分:1)

聆听表单的submit事件,让自己更轻松。提交表单还有其他方法,而不是单击提交按钮。

您要找的是阻止event.preventDefault()的默认操作:

jQuery(document).ready(function() {  

    jQuery("#myform").submit(function(e){
        e.preventDefault();
        jQuery.post(yes.ajaxurl,{action : 'doit'}, function( response) {
            // alert(response);
            //jQuery("#searchtextbox").val(response);
            jQuery("#result").append(response);
            jQuery("#textarea").html(response);
            return false;
        });//end of function
    }); // submit form function finishing here
}); //end of main loop

并为您的表单提供id,以便您可以定位它:

<form id="myform" action="" method="post">