Showing product suggestion while searching woocommerce products

Showing search result based on the selected category using ajax:

Search form:

<form role=”search” method=”get” action=”<?php echo get_permalink( woocommerce_get_page_id( ‘shop’ )); ?>”>
<select name=”category” id=”category”>
<option value=”clothing” selected>Clothing</option>
<option value=”posters”>Posters</option>
<option value=”music”>Music</option>
</select>
<input name=”s” type=”text” onkeyup=”searchfun(this.value);” />
<button type=”submit”>Submit</button>
</form>

js/Ajax function

<script type=”text/javascript”>
function searchfun(value){
var searchq=value;
var category=jQuery(“#category :selected”).text();
jQuery.ajax({
method:”POST”,
url:”<?php bloginfo(‘template_directory’)?>/ajax.php/”,
data:{searchq:searchq,category:category},
success: function(result){
var str = result;
alert(str);
},
error: function(){
alert(‘failure’);
}
});
}
</script>

 

Ajax page : ( here ajax1.php)

<?php require_once(‘../../../wp-load.php’);
$searchq=$_POST[‘searchq’];
$category=$_POST[‘category’];
$args = array( ‘post_type’ => ‘product’, ‘posts_per_page’ => 10, ‘product_cat’ =>$category, ‘orderby’ => ‘rand’ );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$title=get_the_title();
if( strpos( $title, $searchq ) !== false ) {
echo ‘<li><a href=”‘.get_permalink().'”>’.the_title().'</a></li>’;
}
endwhile;
echo “</ul>”;

 

Here we displaying the result as alert, you need to style it based on your requirement.