Variable Visions

Articles Ajax Ajax-Live-Search


tutorials - Ajax and Web-Development.

Ajax Live Search

Published Sat. Sep. 22, 2012


Use this Ajax search on key-up for live searches without a page reload

// Standard search boxes are created using the form tag with a post or get method and action pointing to external file or, if blank, itself. This form queries the database upon the user clicking the submit button

<form method="GET" action="">
<input type="text" name="query" />
<input type="submit" name="submit" value="Search" />
<input type="reset" value="Reset" />
</form>

<?php
if(isset($_GET['submit']))
{
$query=mysql_real_escape_string($_GET['query']);
$query_for_result=mysql_query("SELECT * FROM table WHERE title LIKE '%".$query."%' OR subhead LIKE '%".$query."%' OR description LIKE '%".$query."%' OR keywords LIKE '%".$query."%' OR bodycopy LIKE '%".$query."%'");
echo "<h2>RESULTS FOR: $query </h2><ol>";
while($data_fetch=mysql_fetch_array($query_for_result)){
echo "<li>";?>   
 
<?php echo $data_fetch['headline'];?>
    
 <?php  
echo "</li><hr/>";
}
echo "</ol>";
}
?>








//The below jQuery function using the .post method replacing the form action and method and allows the single input field to trigger the function on key-up allowing for a live Ajax search

<script type="text/javascript">
      function search_function(value) {
        $.post('search_function.php',{partialSearch:value},function(data) {
            $('#ajax_search_results').html(data);      
          });
     }
</script>



<input type="text" onkeyup="search_function(this.value);" value="AJAX LIVE SEARCH" onfocus="if (this.value == 'AJAX LIVE SEARCH') {this.value = '';}" onblur="if (this.value == '') {this.value = 'AJAX LIVE SEARCH';}"/>

<div id="ajax_search_results"></div>





<?php $partialSearch = $_POST['partialSearch'];
echo $_POST['partialSearch'];
$query=mysql_real_escape_string($_POST['partialSearch']);
$query_for_result=mysql_query("SELECT * FROM table_name WHERE title LIKE '%".$query."%' OR subhead LIKE '%".$query."%' OR description LIKE '%".$query."%' OR keywords LIKE '%".$query."%' OR bodycopy LIKE '%".$query."%'");
echo "<h2>RESULTS FOR: $query </h2><ol>";
while($data_fetch=mysql_fetch_array($query_for_result)){
echo "<li>";?>   
 
  <?php echo $data_fetch['headline'];?></a>
         
 <?php  
echo "</li><hr/>";
}
echo "</ol>";
?>




Tag(s): Ajax, jQuery, Live Search, Ajax Search