Load WordPress search results using AJAX

I’m trying to load my Wordpres search results on the same page using AJAX. But I can’t figure out how to show the search results on the page.

I googled for more than an hour and found a lot of codes but most of them didn’t work (for me). The closed I’m getting is with this. Here is what I’ve got so far.

HTML

<section id="toplevel-frontpage">
    <div class="container">
        <div class="block">
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
                    <form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
                        Search:<input type="text" name="str" id="str">
                            <input type="submit" value="send" id="send">
                    </form>
                    <div id="search_results"></div>
                </div>
            </div>
        </div>
    </div>
</section>

jQuery (to stop the search from going to an other page and load the AJAX file)

   $(function() {
        $("#lets_search").bind('submit',function() {
          var value = $('#str').val();
          $.post('wp-content/themes/MyTheme/includes/search-post-results.php',{value:value}, function(data){
          $("#search_results").html(data);
        });
          return false;
       });
   });

search-post-results.php
This is where I’m stuck… If I load a normal loop I get 500 Internal server error… Right now I got this:

<?php session_start(); ?>
<?php
/*
Template Name: Search Page
*/
?>
<?php 
$value = $_POST['value'];
$path = $_SERVER['DOCUMENT_ROOT'];

    include_once $path . '/wp-config.php';
    include_once $path . '/wp-load.php';
    include_once $path . '/wp-includes/wp-db.php';
    include_once $path . '/wp-includes/pluggable.php';

    echo sprintf( __( '%s Search Results for ', 'html5blank' ), $wp_query->found_posts ); echo get_search_query();

?>

I figured I had to include the WordPress Core files so I could use WordPress code, but echo get_search_query() does nothing? $_POST['value']; outputs the input of the search.

Anybody ever had a similar issue or ever made something like this and is willing to share his or her code?

Anyway thanks in advance for the help.

Read more here: Load WordPress search results using AJAX

Leave a Reply

Your email address will not be published. Required fields are marked *