2012-06-23 30 views
6

Tôi cần thiết lập kết quả tìm kiếm wordpress ajax nhưng phương pháp của tôi không truy xuất kết quả khi nút được nhấp và thay vào đó chuyển hướng tôi đến một trang web khác (myurl.com? s = term). Tôi gọi là admin-ajax.php một cách chính xác nhưng thiết lập không chính xác. Bất kỳ ý tưởng nào gây ra sự cố?Làm thế nào để sử dụng Jquery để lấy kết quả tìm kiếm ajax cho wordpress

//Script to activate ajax 
jQuery(document).ready(function($){ 
    var search_val=$("#s").val(); 
    $('#searchsubmit').click(function(){ 
    $.post(
     WPaAjax.ajaxurl, 
     { 
      action : 'wpa56343_search', 
      search_val : search_val 
     }, 
     function(response) { 
      $('#results').append(response); 
     } 
    ); 
    }); 

}); 

//function to setup wp_query 
add_action('wp_ajax_wpa56343_search', 'wpa56343_search'); 
function wpa56343_search(){ 
    global $wp_query; 
    $search = $_POST['search_val']; 
    $args = array(
    's' => $search, 
    'posts_per_page' => 5 
); 
    $wp_query = new WP_Query($args); 

    get_template_part('search-results'); 

    exit; 
} 

//html 

    <div id="my_search"> 
    <form role="search" method="get" id="searchform" action="http://myurl.com/" > 
    <input type="text" value="" name="s" id="s" /> 
    <input type="submit" id="searchsubmit" value="Search" /> 
    </form> 
    </div> 
    <div id="results"></div> 

Trả lời

9

Bạn nên quấn mã của bạn trong document.ready

$(document).ready(function(){ 
    $("#searchsubmit").click(function(e){ 
     e.preventDefault(); 
     var search_val=$("#s").val(); 
     $.post(search.php,{search_string:search_val},function(data){ 
      if(data.length>0){ 
       $("#results").html(data); 
      } 
     }); 
    }); 
}); 

Cập nhật:

$(document).ready(function(){ 
    $("#searchsubmit").click(function(e){ 
     e.preventDefault(); 
     var search_val=$("#s").val(); 
     $.ajax({ 
      type:"POST", 
      url: "./wp-admin/admin-ajax.php", 
      data: { 
       action:'wpa56343_search', 
       search_string:search_val 
      }, 
      success:function(data){ 
       $('#results').append(response); 
      } 
    }); 
}); 

Trong functions.php của bạn

add_action('wp_ajax_nopriv_wpa56343_search', 'wpa56343_search'); // for not logged in users 
add_action('wp_ajax_wpa56343_search', 'wpa56343_search'); 
function wpa56343_search() 
{ 
    // code 
} 
+0

search.php của tôi là trong một child theme. Điều đó có tạo ra bất kỳ sự khác biệt nào trên dòng .post không? –

+0

cung cấp url thích hợp cho search.php của bạn, vị trí của nó, kiểm tra lỗi trong bảng điều khiển. –

+0

yeap đó là vấn đề. Cảm ơn vì đã nắm tay tôi! –

Các vấn đề liên quan