$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>php - Ajax search shows all results when user empties input?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

php - Ajax search shows all results when user empties input?

matteradmin10PV0评论

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.

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.

Share Improve this question edited Nov 2, 2018 at 6:47 joq3 asked Nov 1, 2018 at 21:16 joq3joq3 3813 silver badges21 bronze badges 2
  • What's the code for your data_fetch action? – Jacob Peattie Commented Nov 2, 2018 at 0:55
  • Updated the first post with the complete code. – joq3 Commented Nov 2, 2018 at 6:48
Add a comment  | 

1 Answer 1

Reset to default 1

The regular WordPress search returns all posts if no search term is entered. You'll notice this when using the default search form. If you don't want your AJAX search to behave this way then you need to check if a search term has been entered before doing anything else:

if ( ! empty( $_POST['keyword'] ) && $query->have_posts() ) {

Or better yet, just don't send the AJAX request if there's no search term:

var keyword = jQuery('#keyword').val();

if ( keyword ) {
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: {
          action: 'data_fetch',
          keyword: keyword
        },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });
} else {
    jQuery('#datafetch').html( '' );
}
Post a comment

comment list (0)

  1. No comments so far