1

I have the following code intended to fetch, filter and display custom post on input(onkeyup). However, it sin't working at the moment; I also get a 500 (Internal Server Error) when I open the console. What am I missing?

The PHP:` 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' => 6, 's' => esc_attr( 
  $_POST['keyword'] ), 'post_type' => 'custom_post' ) );
  if( $the_query->have_posts() ) :
    while( $the_query->have_posts() ): $the_query->the_post(); ?>
  <div class="cell s_result_box">
            <div class="title"><a href="<?php echo esc_url( post_permalink() ); ?>"><?php 
             the_title();?></a></li></div>

            <div class="content"><?php the_content(); ?></div>
            <div class="meta"><span class=""><?php the_post_meta() ?></span> - <span 
            class=""><?php get_the_date(); ?></span></div>
            <div class="dividerline"></div>
            </div>
        </div>
       <?php endwhile; ?>

   add_action( 'wp_footer', 'ajax_fetch' );
   function ajax_fetch() {
   ?>
   <script type="text/javascript">
function fetchResults() {
    var keyword = jQuery('#searchInput').val();
    if(keyword == "" || keyword == 0){
        jQuery('#datafetch').html( " " );
        jQuery("#search-message").fadeIn();
        return;
    } else {
        jQuery("#search-message").fadeOut();
        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>

      //The search form and results div
      <form class="t_margin_0" autocomplete="off">
              <input type="search" name="s" class="t_margin_0 dir_search" 
        placeholder="Search by name, location, department…" id="searchInput" 
        onkeyup="fetchResults()">
            </form>

     <div class="grid-x" id="datafetch"></div>`

1 Answer 1

0

The 500 error means your ajax url is not working. Try using an external js file and wp_localize_script

More info in the codex.

2
  • Apart from the 500 server error, the whole code doesn't work... still can't figure out why.
    – jeno
    May 4, 2020 at 21:23
  • It won't work unless you solve the ajax 500 error. Then debug the rest of your code if necessary.
    – shanebp
    May 4, 2020 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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