The JavaScript should be:
<script>
jQuery( document ).ready(function ( $ ) {
$( "#searchform" ).on( "submit", function ( ev ) {
ev.preventDefault();
$.post(
"<?php echo admin_url( 'admin-ajax.php' ) ?>",
{
action: "wpa56343_search",
search: $( "#s" ).val()
},
function ( response ) {
$( "body" ).append( response );
}
);
});
});
</script>
And the AJAX handler code in your functions.php
should be:
function wpa56343_search() {
if ( ! isset( $_POST['search'] ) )
exit;
query_posts(
array(
'posts_per_page' => 5,
'no_found_rows' => true,
'post_type' => get_post_types( array( 'public' => true ) ),
's' => wp_unslash( ( string ) $_POST['search'] ),
)
);
get_template_part( 'includes/search-post-results' );
exit;
}
add_action( 'wp_ajax_nopriv_wpa56343_search', 'wpa56343_search', 100 );
add_action( 'wp_ajax_wpa56343_search', 'wpa56343_search', 100 );
Typically you should avoid query_posts
, but it’s perfectly valid in this context as we’re setting up an isolated global query for search-post-results.php
to use.