Can't load search results with ajax

I'm trying to load search results on my page without reloading. I tried multiple approaches already, but I still ca

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.

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.

Share Improve this question edited Aug 26, 2015 at 12:25 squid asked Aug 26, 2015 at 10:51 squidsquid 33 bronze badges 10
  • Probably because WPaAjax is not defined - can you link to the original solution? – TheDeadMedic Commented Aug 26, 2015 at 10:55
  • Yeah. I was trying this: wordpress.stackexchange/questions/56343/… and this: stackoverflow/questions/11166981/… . Initially I didn't even use WPaAjax, but the result was still the same. – squid Commented Aug 26, 2015 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 Commented Aug 26, 2015 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 Commented Aug 26, 2015 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 Commented Aug 26, 2015 at 11:09
 |  Show 5 more comments

1 Answer 1

Reset to default 1

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742279573a4414234.html

相关推荐

  • Can&#39;t load search results with ajax

    I'm trying to load search results on my page without reloading. I tried multiple approaches already, but I still ca

    1天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信