Use ajax to filter mysql results with multiple checkbox option

Hi,
i am trying to build a search filter (like ebay site) using checkboxes. okay let me explain what i have done.
So, to get an idea of what type of thing i want please visite ebay site. i am also building ebay site as my project. visite this page please for better understanding https://www.ebay.com/sch/Other-Video-Games-Consoles/187/bn_1865232/i.html?_fsrp=1
i have build a web page completely look like this.
So, what i have done?
i have a search filter in which i have brand, plateform and model in which i get values from database.
Here is my code to get value from database same for plateform and model

<article class="search-item">
	<h6 id="show">Brand</h6>
	<ul>
	    <?php 
		if($cid)
                     {
                         $sql = "SELECT * FROM brands WHERE Cat_id = $cid";
                          $query = mysqli_query($connect,$sql);
                           $rs = mysqli_fetch_row($query);
                            if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                         while($brandrow = mysqli_fetch_array($query))
                            {
                              echo "<li><input type=\"checkbox\" name=\"brand\" value=\"".$brandrow['brand_id']."\" class=\"bcheckid check\" >".$brandrow['BrandName']."<li>";			
                          }
                        }
                    }
		?> 
	</ul>
</article>

i try using jquery ajax to search filter data on alerting a single value it works and show result but when i send this value using $.get method in jquery ajax i gives all html web page code, but i wants only the value. i am confused please help me. i only wants to value in $_GET method so please don’t use post method.
here is my jquery ajax code


        $(document).ready(function(){
            $(".check").click(function(){
            var cid = <?php echo $cid = $_GET['cid'] ?>;
            //alert(cid);
                //for brand 
                var brand = new Array();
                $("input[name=brand]:checked").each(function() {                   
                   brand.push($(this).val());
                   //alert(brand);  
                });
                //for plateform
                var plateform = new Array();
                 $("input[name=plateform]:checked").each(function() {                   
                    plateform.push($(this).val());
                    //alert(plateform);  
                 });

                 //for model 
                var model = new Array();
                $("input[name=model]:checked").each(function() {                   
                    model.push($(this).val());
                    //alert(model);  
                });
                 //$.get("item.php",{cid: cid,brand: brand,plateform: plateform,model: model
				var formdata = $("#checkform").serialize();
				$.ajax({
						type:"get",
						url:"result.php",
						data:formdata//only input						
				});
			});
        });
         

Here is my item.php code where i get search filter result.

$cid = $_GET['cid'];
	$plateform = $_GET['plateform'];
	$brandid = $_GET['brand'];
	$model_id  = $_GET['model'];
		if(!empty($cid))
		{
			$value = "Cat_id = $cid ";
		}
		else
		{
			$value = "";
		}
		
		$and = " AND ";
		if(!empty($brandid))
		{
			$brand = $and."brand_id = ".implode(",", $brandid); 
		}
		else 
		{
			$brand ="";
		}
		if(!empty($plateform))
		{
			$plateform_id = $and."plateform_id IN (".implode(",", $plateform)."$plateform)"; 
		}
		else 
		{
			$plateform_id ="";
		}
		if(!empty($model_id))
		{
			$model = $and."model_id = ".implode(",", $model_id); 
		}
		if($cid == 3)
		{
			$model ="";
		}

		
		
		
		
        echo $prodsql = "SELECT * FROM products
				INNER JOIN `condition` ON `products`.`condition_id` = `condition`.`condition_id`
				WHERE  $value $brand $plateform_id $model $pvalue  
				LIMIT $paginate->start, $paginate->limit;";
    

Again Please help me and thank you soooo much in advance. and sorry for my bad english.

Well, I assume you have a form element around the whole thing with ID checkform.
The script is likely failing because serializing the form doesn’t include the cid.

			var formdata = $("#checkform").serialize();
            formdata.cid = cid

Also i’m not sure what you’re expecting ‘item.php’ (which you’ve called result.php in your ajax code…) to output, but you’ve told it to echo the query, rather than execute the query and echo the jsonified result.
Also you’re not doing anything with the result of your ajax statement. Define a success clause to handle your result.

In your PHP code, what happens to the query if there is no cid value selected? You create a variable called $value which either has a condition for Cat_id or is blank, but if it’s blank, then your next selection criterion starts with " AND ", which would throw a query syntax error if you were executing the query.

It seems that, even when you pass cid through as @m_hutley noted above, it is valid for it to have no value, as otherwise you’d set an error flag. So, if it has no value, you need to deal with not starting your subsequent conditions with AND if it is not required.

Your code for selecting brand and model_id seems wrong as well, unless those columns actually contain comma-separated lists of values, which is not often recommended for database table layouts.

oh sorry i call item.php page result.php my mistake.

Well if there is no cid value No Record Found shows.
i am confused, i just want that when i check a brand, plateform or model onclick event its show me a result of related data at item.php page where products result shown.Thanks.Please help and i use implode function in IN mysql function so that i am able to it shows result of multiple values.

Hi, m_hutley, Thanks for reply, formdata.cid = cid what’s that i don’t understand and how i sent cid value? and other thing when i use success function in ajax and try to alert or get output and specific id it shows all item.php code or at sepcific it shows whole web page at that place. but i just wants is the value of brand,plateform and model. Please Help me. Thanks.

Because (I’m assuming) you dont include cid as a form .[quote=“romanmuhammad7, post:1, topic:292942”]
var formdata = $(“#checkform”).serialize();
[/quote]

this line takes all of the inputs, textareas, and anything with a ‘name’ attribute inside that form that have a value, and sticks them into the object that you send along to result.php.[quote=“romanmuhammad7, post:1, topic:292942”]
var cid = <?php echo $cid = $_GET[‘cid’] ?>;
[/quote]

this line put a cid varaiable into your javascript set.

formdata.cid = cid
This then takes the value you set in quote 2, and adds it to the variable you created in quote 1.

If there IS a cid input into the form, you dont need that part.

if you send an AJAX, it gets whatever the webserver sends it. If you want to only get information, then change result.php to only send the information.

Yeh now everything works well as i used $.get method in ajax jquery but i have a little problem when i check the box is shows related result but i also duplicated the same page where result shows here is a result before and after checkbox checked.
image after click checkbox shows result


image before search result i mean in normal mode.
i am going to upload second image in second reply please must check it.
Now i clear you.
i have two filtes side_search.php and item.php filter. in side_search.php file i have all checkboxes and i require it in item.php file, and i get this result with ajax jquery so page not loads. i paste code for these two files please check whats happening. And Thank you so much for helping me.

Code For side_search.php

<?php
require_once("data_connect.php");
$cid = $_GET['cid'];

 ?>
 <!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
 <aside class="aside-bar">
			<h3 id="h3">Search items</h3>
			<form action="item.php" method="get" name="search_form" id="checkform">
				<article class="search-item">
					<h6>Brand</h6>
					<ul>
						<?php 
							if($cid)
                            {
                                $sql = "SELECT * FROM brands WHERE Cat_id = $cid";
                                $query = mysqli_query($connect,$sql);
                                $rs = mysqli_fetch_row($query);
                                if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                                    while($brandrow = mysqli_fetch_array($query))
                                    {
                                        echo "<li><input type=\"checkbox\" name=\"brand\" value=\"".$brandrow['brand_id']."\" class=\"bcheckid check\" > ".$brandrow['BrandName']."<li>";			
                                    }
                                }
                            }
						?> 
					</ul>
				</article>
				<article class="search-item">
					<h6>Plateform</h6>
					<ul>
						<?php 
							if($cid)
                            {
                                $sql = "SELECT * FROM plateform WHERE Cat_id = $cid";
                                $query = mysqli_query($connect,$sql);
                                $rs = mysqli_fetch_row($query);
                                if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                                    while($pltrow = mysqli_fetch_array($query))
                                    {
                                        if($pltrow['plateform_id'] == $plateform)
                                        {
                                            echo "<li><input type=\"checkbox\" name=\"plateform\" value=\"".$pltrow['plateform_id']."\" class=\"pcheckid check\" checked>".$pltrow['PlateformName']."<li>";
                                        }
                                        echo "<li><input type=\"checkbox\" name=\"plateform\" value=\"".$pltrow['plateform_id']."\" class=\"pcheckid check\" >".$pltrow['PlateformName']."<li>";			
                                    }
                                }
                            }
                           
						?>
					</ul>
				</article>
				
			<article class="search-item">
                <h6>Model</h6>
                <ul>
					<?php
						if($cid)
                            {
                                $sql = "SELECT * FROM model WHERE Cat_id = $cid";
                                $query = mysqli_query($connect,$sql);
                                $rs = mysqli_fetch_row($query);
                                if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                                    while($modelrow = mysqli_fetch_array($query))
                                    {
                                        echo "<li><input type=\"checkbox\" name=\"model\" value=\"".$modelrow['model_id']."\" class=\"mcheckid check\" >".$modelrow['ModelName']."<li>";			
                                    }
                                }
                            }                          
					?>
                </ul>
            </article>
				
			<!--<article class="sub-btn">
					<input type="submit" name="search" value="submit">
				</article> -->
			</form>
		</aside>
		
	<script>
		/*
		    $(document).ready(function(){
            $(".check").click(function(){
            var cid = <?php echo $cid = $_GET['cid'] ?>;
            //alert(cid);
			if(cid){
				var brand = new Array();
               $("input[name=brand]:checked").each(function() {                   
                   brand.push($(this).val());
                   //alert(brand);  
                });
                //for plateform
                var plateform = new Array();
                 $("input[name=plateform]:checked").each(function() {                   
                    plateform.push($(this).val());
                    //alert(plateform);  
                 });
				//for model 
                 var model = new Array();
                 $("input[name=model]:checked").each(function() {                   
                    model.push($(this).val());
                    //alert(model);  
                });
				
				var formdata = $("#checkform").serialize();
                 $.get("result.php",{cid: cid,brand: brand, plateform: plateform, model: model});
			}				
			});
        });
		*/
		
	</script>
</body>
</html>

Code for item.php file

<?php 
	error_reporting(E_ALL ^E_NOTICE ^E_WARNING);
	require_once("data_connect.php");
	 //session_start();
	// for pagination
	//step 1 declare class of pagination
	require_once("classes/Pagination.php");
	#Step 2 Assign Basic Variables
    $page_limit = 20;
    $total = 0;
    $paging = "";
    $max_pages = 10;
	#Step 3 get total records.
    $cntrs    = mysqli_query($connect,"SELECT count(*) from products");
    $totalrow = mysqli_fetch_row($cntrs);
    $total  =  $totalrow[0];
	#Step 3 Tell the page name
	$_pageurl = "product_page.php";
	#Step 3 Create class object
	$paginate = new Paginate($page_limit, $total, $_pageurl, $max_pages);
	$paging = $paginate->displayUl();
	$page = $paginate->currentPage;
	$paginate->start = $paginate->start -1;
	
	$cid = $_GET['cid'];
	$plateform = $_GET['plateform'];
	$brandid = $_GET['brand'];
	$model_id  = $_GET['model'];
	
	
		if(!empty($cid))
		{
			$value = "Cat_id = $cid ";
			$and = " AND ";
			if(!empty($brandid))
			{
				$value .= $and."brand_id IN(".implode(",",$brandid).")";
			}
			else 
			{
				$value .= "";
			}
			if(!empty($plateform))
			{
				$value .= $and."plateform_id IN(".implode(",",$plateform).")";
			}
			else 
			{
				$value .= "";
			}
			if(!empty($model_id))
			{
				$value .= $and."model_id IN(".implode(",",$model_id).")";
				
			}
			else 
			{
				$value .= "";
			}
			if($cid == 3)
			{
				
			}
		}
		else
		{
			$value = "";
		}

		
		
		
		
        $prodsql = "SELECT * FROM products
				INNER JOIN `condition` ON `products`.`condition_id` = `condition`.`condition_id`
				WHERE  $value 
				LIMIT $paginate->start, $paginate->limit;";
    
   
	if(!empty($prodsql))
	{
		$prodres = mysqli_query($connect,$prodsql);
		
		//$numrows = mysqli_num_rows($prodres); //echo $numrows; calculating number of rows 
		$dataArray = array();
		while($row = mysqli_fetch_row($prodres))
		{
			array_push($dataArray,$row);
		}
		//var_dump($dataArray);
	}
?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Search your products</title>
	<link rel="stylesheet" href="css/style.css">
	<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
</head>
<body id="body">

	<?php
		#require("header.php");
		require('include/main_header.php');
	?>
	
	<section class="link-tree">
        <a href="index.php">ebay</a> 
			<i class="link-divider"> &rsaquo; </i> 
		<a href="products.php">products</a> 
			<i class="link-divider"> &rsaquo; </i>
		<a href="item.php">item</a> 
			<!--<i class="link-divider"> > </i>-->
    </section>
	
	<section class="box-wrapper">
		<h2>Video Games &amp; Consoles</h2>
		
		<?php //require_once("side_search.php"); ?>
		
		 <aside class="aside-bar">
			<h3 id="h3">Search items</h3>
			<form action="item.php" method="get" name="search_form" id="checkform">
				<article class="search-item">
					<h6>Brand</h6>
					<ul>
						<?php 
							if($cid)
                            {
                                $sql = "SELECT * FROM brands WHERE Cat_id = $cid";
                                $query = mysqli_query($connect,$sql);
                                $rs = mysqli_fetch_row($query);
                                if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                                    while($brandrow = mysqli_fetch_array($query))
                                    {
                                        echo "<li><input type=\"checkbox\" name=\"brand\" value=\"".$brandrow['brand_id']."\" class=\"bcheckid check\" > ".$brandrow['BrandName']."<li>";			
                                    }
                                }
                            }
						?> 
					</ul>
				</article>
				<article class="search-item">
					<h6>Plateform</h6>
					<ul>
						<?php 
							if($cid)
                            {
                                $sql = "SELECT * FROM plateform WHERE Cat_id = $cid";
                                $query = mysqli_query($connect,$sql);
                                $rs = mysqli_fetch_row($query);
                                if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                                    while($pltrow = mysqli_fetch_array($query))
                                    {
                                        if($pltrow['plateform_id'] == $plateform)
                                        {
                                            echo "<li><input type=\"checkbox\" name=\"plateform\" value=\"".$pltrow['plateform_id']."\" class=\"pcheckid check\" checked>".$pltrow['PlateformName']."<li>";
                                        }
                                        echo "<li><input type=\"checkbox\" name=\"plateform\" value=\"".$pltrow['plateform_id']."\" class=\"pcheckid check\" >".$pltrow['PlateformName']."<li>";			
                                    }
                                }
                            }
                           
						?>
					</ul>
				</article>
				
			<article class="search-item">
                <h6>Model</h6>
                <ul>
					<?php
						if($cid)
                            {
                                $sql = "SELECT * FROM model WHERE Cat_id = $cid";
                                $query = mysqli_query($connect,$sql);
                                $rs = mysqli_fetch_row($query);
                                if($rs == 0)
                                {
                                    echo "";
                                }
                                else 
                                {
                                    while($modelrow = mysqli_fetch_array($query))
                                    {
                                        echo "<li><input type=\"checkbox\" name=\"model\" value=\"".$modelrow['model_id']."\" class=\"mcheckid check\" >".$modelrow['ModelName']."<li>";			
                                    }
                                }
                            }                          
					?>
                </ul>
            </article>
				
			<!--<article class="sub-btn">
					<input type="submit" name="search" value="submit">
				</article> -->
			</form>
		</aside>
		
		
			<section class="sec-page">
					<?php
		if(!empty($dataArray)){
			for($i=0;$i<count($dataArray);$i++)
			{
		?>
				<form name="form<?php echo $i ?>" method="post" action="create_cart.php">
					<!-- Some Hidden values used to add remove and udate also for checkout -->
					<input name="id" 	type="hidden" value="<?php echo $dataArray[$i][0];?>">
					<input name="name" 	type="hidden" value="<?php echo $dataArray[$i][1];?>">
					<input name="image" type="hidden" value="<?php echo $dataArray[$i][2];?>">
					<input name="price" type="hidden" value="<?php echo $dataArray[$i][3];?>">
					<input name="item_loc" type="hidden" value="<?php echo $dataArray[$i][20];?>">
					<input name="formate" type="hidden" value="<?php echo $dataArray[$i][21];?>">
					<input name="delivery_opt" type="hidden" value="<?php echo $dataArray[$i][24];?>">
					<input name="Cat_id"  type="hidden" value="<?php echo $dataArray[$i][12];?>"> 
					<input name="quantity"  type="hidden" value="<?php echo $dataArray[$i][28];?>"> 
					
					<article class="prod_item">
						<figure class="img-box">
							<?php echo "<img src =images/".$dataArray[$i][2]."  width=100% >" ?>
						</figure>
						<article class="item_detail_box">
							<h4><a href=""><?php echo $dataArray[$i][1]; ?></a></h4>
							<p>Condition:<?php echo $dataArray[$i][12]; ?></p>
							<h5>Price:$<?php echo $dataArray[$i][3]; ?></h5>
							<span><?php echo $dataArray[$i][20]; ?></span>
							<p><?php echo $dataArray[$i][21]; ?></p>
							<p><?php echo $dataArray[$i][24]; ?></p>
							<!--<a href="addtocart.php?pid=<?php //echo $dataArray[$i][0] ?>" class="cart-btn">Add to Cart</a>-->
							<input type="submit" name="sub_btn" Value="Add to Cart" class="cart-sub-btn">
						</article>
					</article>
				</form>
			
		<?php 
			}
		}
		

		else
		{
			echo "<p style=\"font-family:segoe ui;color:grey;text-align:center;\">Record Not Found</p>";
		}
		?>
				
			<article class="pagination">
		  <?php echo $paging; ?>
		</article>
		<br>
		<article style="float:right;font-size:18px;">
			<span class="back-btn"><a href="products.php">&lsaquo; Back</a></span>
		</article>
	</section>

	 </section>
	

	
	
	<?php
		#require("footer.php");
		require('include/main_footer.php');
	?>
	
	<input type="text" name="catid" value="<?php echo implode(",",$cid); ?>">
	<input type="text" name="brand" value="<?php echo implode(",",$brandid); ?>">
	<input type="text" name="plateform" value="<?php echo implode(",",$plateform); ?>">
	<input type="text" name="model" value="<?php echo implode(",",$model_id); ?>">
	
	
	<script>
		

        $(document).ready(function(){
            $(".check").click(function(){
            var cid = <?php echo $cid = $_GET['cid'] ?>;
            //alert(cid);
			if(cid){
				var brand = new Array();
                $("input[name=brand]:checked").each(function() {                   
                   brand.push($(this).val());
                   //alert(brand);  
                });
                //for plateform
                var plateform = new Array();
                 $("input[name=plateform]:checked").each(function() {                   
                    plateform.push($(this).val());
                    //alert(plateform);  
                 });
				//for model 
                 var model = new Array();
                 $("input[name=model]:checked").each(function() {                   
                    model.push($(this).val());
                    //alert(model);  
                });
				
				//var formdata = $("#checkform").serialize();
                 $.get("item.php",{cid: cid,brand: brand, plateform: plateform, model: model},function(data){
					 $(".sec-page").html(data);
				 });
			}	
				
			});
        });
  		
	</script>
</body>
</html>

Here is my image before search

So… again, the way you’ve coded it, whatever item.php hands back is what goes into the window. You’ve told item.php to render the header and sidebar, so it renders the header and sidebar.

It’s doing exactly what you told it to do. If thats not what you want, change it…

Oh Thank you so much my problem solved. Thank you so much for helping me.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.