jquerysearchjquery-pagination

Search paginated results with jQuery


I have developed a single page app that shows all the entries off a database table. The results are paginated and are presented without refreshing the whole page. The html part of my code is this:

<p>Search by Last Name:</p>
  <div class="form-group">  
    <div class="input-group">
        <form method="post">
          <input type="text" name="search" id="search" placeholder="Search by Last Name" class="form-control" />
          <input type="submit" id="submitbtn"/>
        </form>
    </div>  
  </div> 
<div class="table-responsive" id="pagination_data">
</div>

The jQuery code is the following:

<script>  
 $(document).ready(function(){

      load_data();

      function load_data(page,search)  
      {  
           $.ajax({  
                url:"pagination.php",  
                method:"POST",  
                data:{page:page, search:search},  
                success:function(data){  
                     $('#pagination_data').html(data);  
                }  
           });  
      }  
      $(document).on('click', '.pagination_link', function(){  
           var page = $(this).attr("id");  
           load_data(page);  
      });
      $(document).on('click', '#submitbtn', function(){  
           var page = $(this).attr("id");
           var search = $('#search').val();
           load_data(page,search);  
      });

 });
 </script> 

I want to be able to search the results without changing to another page. Currently, the pagination is working correctly. I just want to find a way to send the value of #search to the server-side and use it in a query. The way I have used above to send the value of #search is not working.


Solution

  • Your Submit button is a form input and I don't believe the click event is firing. If you change:

    $(document).on('click', '#submitbtn', function(){  
    

    to

    $(document).on('submit', '#submitbtn', function(e){  
    

    You should see the function fire. Note that I added parameter e to the anonymous function. This will allow you to perform e.preventDefault(); inside the function which will stop the default form submission. Typically, this would redirect the browser to the address pointed to in the submit's action attribute