Just managed to get ajax live search working, which means I can get the results instantly when I enter characters in the input. The problem appears when I clear the input, it will show all results. When the page first loads it will not show everything. And I don't want it to show all the results when the user empties the input.
This is the current code: Input:
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch">Search results will appear here</div>
Ajax fetch JS:
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch() {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'data_fetch',
keyword: jQuery('#keyword').val()
},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
Ajax fetch PHP:
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch() {
$query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'visitor' ) );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post(); ?>
<div id="check-in-visitor">
<a href="mailto:<?php the_author_email(); ?>"><?php the_title(); ?><?php the_content(); ?></a>
</div>
<?php
}
wp_reset_postdata();
}
else {
?>
<h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
<div class="alert alert-info">
<p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
</div>
<?php
}
die();
}
I understand why it happens, because on user keyup it will show the results, and when nothing is in the input, everything is shown. But I cannot figure out how to solve this.
data_fetch
action?