Search code examples
phpjqueryajaxpdoajaxform

How do I run my php function through Ajax and loop through the results?


So I am trying to build a simple search function for my website, and I don't want to have to refresh the page to return results. The code that i have here works perfectly, But I don't know how to Implement this using Jquery. I mainly have 2 pages, index.php and library.php

The section from the library.php that handles the search is as follows.

require_once('auth/includes/connect.php');
class MainLib
{
 public function search($keyword){
        try {
            $db = DB();
            $query = $db->prepare("SELECT houses.*, users.user_id FROM houses JOIN users ON users.user_id=houses.ownerid WHERE houses.location=:keyword");
            $query->bindParam(":keyword", $keyword, PDO::PARAM_STR);
            $query->execute();
            if ($query->rowCount() > 0) {
                return $query->fetchAll(PDO::FETCH_OBJ);
                
            }
        } catch (PDOException $e) {
            exit($e->getMessage());
        }
    }
}

And the Section From the index.php that prints the results is as follows

<?php          $hdata = new MainLib();
                                            if(isset($_POST[$search])){
                                            $houses = $hdata->search($search); // get user details
                                            foreach($houses as $house){
                                              ?>

                                        <div class="single-property-box">
                                            <div class="property-item">
                                                <a class="property-img" href="#"><img src="houses/<?php echo $house->main_image ?>" alt="#">
                                                </a>
                                                <ul class="feature_text">
                                                    <?php 
                                                    if($house->featured=='true'){
                                                    ?>
                                                    <li class="feature_cb"><span> Featured</span></li>
                                                    <?php }?>
                                                    <li class="feature_or"><span><?php echo $house->gender ?></span></li>
                                                </ul>
                                                <div class="property-author-wrap">
                                                    <a href="#" class="property-author">
                                                        <img src="dash/auth/users/<?php echo $house->profilepic ?>" alt="...">
                                                        <span><?php echo $house->title ?>. <?php echo $house->surname ?></span>
                                                    </a>
                                                    <ul class="save-btn">
                                                        <li data-toggle="tooltip" data-placement="top" title="" data-original-title="Bookmark"><a href="#"><i class="lnr lnr-heart"></i></a></li>
                                                        <li data-toggle="tooltip" data-placement="top" title="" data-original-title="Add to Compare"><a href="#"><i class="fas fa-arrows-alt-h"></i></a></li>
                                                    </ul>
                                                   
                                                </div>
                                            </div>
<?php }}?>

So How would I accomplish the same result without having to reload the page every time ?


Solution

  • Here's a basic ajax search form setup using jQuery. Note that the search input is in a form with onsubmit="return false" - this is one way to prevent the default form submission which would trigger a page reload.

    The button calls a function which gets the value of the search input, makes sure it's not blank, and puts it into an ajax function

    The PHP page will receive the search term as $_GET['term'] and do it's thing. In the end, you will output (echo) html from your PHP functions, which the ajax done() callback will put into your search_results div. There are more optimized ways of transferring the data back - maybe a minimal json string that contains just the info you need for results, and your javascript takes it and inflates it into an html template. For large search results, this would be better because it means less data getting transferred and faster results.

    function search() {
      let term = $('#search_term').val().trim()
      if (term == "") return; // nothign to search
      $.ajax({
        url: "searchFunctionPage.php",
        method: 'get',
        data: {
          term: term
        }
      }).done(function(html) {
        $('#search_results').html(html);
      });
    
      // sample data since we dont have the ajax running in the snippet
      let html = 'Found 100 results.. <div>result 1</div><div>...</div>';
      $('#search_results').html(html);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form onsubmit='return false;'>
      <input type='text' placeholder="Type in your search keyphrase" id='search_term' />
      <button type='button' onclick='search()'>Search</button>
    </form>
    <div id='search_results'></div>