0

I'm trying to load search results on my page without reloading. I tried multiple approaches already, but I still can't make it work, despite using someone else's confirmed solution.

Please find the code below:

  • search-post-results.php (in includes folder)

    <?php
    /* Template Name: Search Post Results */        
    ?>             
    <div class="contentarea">
        <div id="content" class="content_right">  
                 <h3>Search Result for : <?php echo "$s"; ?> </h3>       
                     <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>    
                         <div id="post-<?php the_ID(); ?>" class="posts">        
                             <article>        
                                 <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><h4>          
                             </article> 
                         </div>
                     <?php endwhile; ?>
                     <?php endif; ?>
        </div>
    </div>
    
  • functions.php

    add_action('wp_ajax_nopriv_wpa56343_search', 'wpa56343_search',100);
    add_action('wp_ajax_wpa56343_search', 'wpa56343_search',100);
    function wpa56343_search()
      {
        global $wp_query;
        $search = $_POST['search_val'];
        $args = array(
          's' => $search,
          'posts_per_page' => 5
        );
        $wp_query = new WP_Query($args);
        get_template_part('includes/search-post-results');
        exit;
      }
    
  • HTML form

    <div id="my_search">
        <form role="search" method="get" id="searchform"  >
            <input type="text" value="" name="s" id="s" />
            <input type="submit" id="searchsubmit" value="Search" />
        </form>
    </div>
    
  • jQuery

    <script>
    jQuery(document).ready(function () {
      jQuery("#searchsubmit").click(function (e) {
          e.preventDefault();
          var search_val = jQuery("#s").val();
          jQuery.post(
              "<?php echo admin_url('admin-ajax.php'); ?>", {
                action:'wpa56343_search',
                search_string:search_val
              }, function (response) {
                jQuery('body').append(response);
              }
          }
       });
    });
    </script>
    

Instead of getting results on the same page, using my template, I just go to url/s?=search_val and a default search results template is loaded.

Thanks for help.

E: Slowly moving forward. After using the above code the error I'm getting is Uncaught ReferenceError: wpa56343_search is not defined.

  • Probably because WPaAjax is not defined - can you link to the original solution? – TheDeadMedic Aug 26 '15 at 10:55
  • Yeah. I was trying this: wordpress.stackexchange.com/questions/56343/… and this: stackoverflow.com/questions/11166981/… . Initially I didn't even use WPaAjax, but the result was still the same. – squid Aug 26 '15 at 10:57
  • So I'm guessing you've just got the JavaScript inline in a template, as opposed to putting it in a file and enqueuing it? – TheDeadMedic Aug 26 '15 at 11:00
  • Yessssss. Should I enqueue it instead? Oh, I see it now. you mean using the wp_localize_script bit. I see it now, my bad... I 'm just editing my main question with my previous code that didn't work either. – squid Aug 26 '15 at 11:07
  • No need - since we can run PHP in this context, just replace WPaAjax.ajaxurl with "<?php echo admin_url( 'admin-ajax.php' ) ?>" - don't forget the quotes! – TheDeadMedic Aug 26 '15 at 11:09
0

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.

  • Yes! Works like a charm. Many thanks! Out of curiosity - the error I mentioned above... Do you have any idea why I couldn't use the wpa56343_search action in my code? – squid Aug 26 '15 at 12:49
  • It was a JS error, not to do with your AJAX handler - maybe you were missing quotes or had UTF-8 alternative quotes around wpa56343_search in your code. – TheDeadMedic Aug 26 '15 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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