0

I tried to configure search area in wordpress using ajax, so i add this code into functions.php

<?php
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( array( 'posts_per_page' => 5, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a>

        <?php endwhile;
  wp_reset_postdata();  
 else: 
  echo '<h3>No Results Found</h3>';
    endif;
    die();
}

// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">

$("input").keyup(function() {

 var keyword = jQuery('#searchInput').val();
 if(keyword == ""){
  jQuery('#datafetch').html("");
 } else {
  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 );
   }
  });
  });
 }

</script>
<?php
}
?>

then in my template page i added

<div class="container ">

  <div class="d-flex justify-content-center ">

      <div class="searchbar">

 <input id="searchInput" class="search_input" type="text" name=""  placeholder="Search...">

   <a href="#" class="search_icon"><i class="fas fa-search"></i></a>

 </div>

 </div>

</div>
<div id="datafetch">
</div>

but nothing appear when i fill the search text , did i miss something ? thank you for your help

1
  • do you have any javascript errors in your browser's error console?
    – Milo
    Commented Jan 19, 2019 at 21:09

1 Answer 1

0

You are using post_permalink() that is deprecated. Please use get_permalink() or the_permalink() and also make sure that ajax function is called successfully by simply returning any string from ajax function.

Not the answer you're looking for? Browse other questions tagged or ask your own question.