Price Range Slider Filter in PHP with MySQL using jQuery and Ajax

Range slider is very useful to add filter feature to the data list. Range slider is mostly used to filter data between two values. Mostly the price filter uses a range slider to filter items by price range in the web application. The price range slider allows the user to filter the record set by selecting the price range instead of entering the price manually.

Price range filter functionality can be implemented in PHP using jQuery and Ajax. In this tutorial, we will create a price range slider using jQuery and add filter functionality to the data list with PHP & MySQL. The price filter is a required feature in the product listing and the range slider is a perfect choice for a price filter. Here we’ll show how you can easily add a price range slider to the products list using jQuery in PHP and filter products by price range using jQuery, Ajax, PHP & MySQL.

In this example script, the following functionality will be implemented to make a price range filter with slider in PHP.

  • Fetch products from the database and list them on the web page.
  • Create a range slider and add a price range filter to the product list.
  • Filter products by price range with jQuery Ajax using PHP and MySQL.

Before getting started integrating the price range filter in PHP, take a look at the file structure.

price_range_slider_filter_in_php/
├── dbConfig.php
├── index.php
├── fetchProducts.php
├── js/
│   ├── jquery.min.js
│   ├── jquery.range.js
│   └── jquery.range.css
└── css/
    └── style.css

Create Database Table

To store the products data a table is required in the database. The following SQL creates a products table with some basic fields in MySQL database.

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `price` float(6,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the MySQL database. Specify the database credentials, host ($dbHost), username ($dbUsername), password ($dbPassword), and database name ($dbName).

<?php 

// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

?>

Products List with Price Range Slider Filter (index.php)

Create Price Range Slider:
jQuery is used to create a range slider and initiate ajax request, so, include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

We will use jRange plugin to build a range slider using jQuery for selecting price range. The jRange is a lightweight jQuery plugin that helps to convert an input field to a range slider.

<link rel="stylesheet" href="js/jquery.range.css">
<script src="js/jquery.range.js"></script>

Use jRange() method to initiate jRange plugin and specify the input selector where the range slider will be attached.

  • from – Min value of the slider.
  • to – Max value of the slider.
  • step – Interval between min and max values for each step (Default: 1).
  • format – Text format to display in pointer label (Default: %s).
  • width – Slider width (Default: 300).
  • showLabels – Display pointer label (Default: true).
  • isRange – Whether the slider represents a range (Default: false).
<script>
$(function(){
    $('#price_range').jRange({
        from: 0,
        to: 500,
        step: 50,
        format: '$%s USD',
        width: 300,
        showLabels: true,
        isRange : true
    });
});
</script>

The HTML input field is defined in the next step, the element ID should be specified here as a selector (#price_range).

Products List with Price Range Filter:
Initially, all the products are fetched from the database and listed on the web page. Also, a price range slider is added to the list for filtering the products by price.

  • Create an HTML input field where range slider will be added.
  • Define an HTML button that will trigger the JavaScript function (filterProducts()) to filter records via Ajax.
  • Fetch product data from the database using PHP and MySQL.
<div class="search-panel">
    <p><input type="hidden" id="price_range" value="0,500"></p>
    <button onclick="filterProducts()" class="btn btn-outline-primary">Filter Products</button>
</div>

<div id="productContainer">
<?php 
    
// Include database configuration file
    
include "dbConfig.php";
    
    
// Fetch products from database
    
$query $db->query("SELECT * FROM products WHERE status = 1 ORDER BY created DESC");
    
    if(
$query->num_rows 0){
        while(
$row $query->fetch_assoc()){
        
?> <div class="list-item"> <h2><?php echo $row["name"]; ?></h2> <h4>Price: $<?php echo $row["price"]; ?></h4> </div> <?php 
        
}
    }else{
        echo 
'<p>Product(s) not found...</p>';
    }
    
?> </div>

Price Range Filter with jQuery and Ajax:
The filterProducts() function initiates an Ajax request to handle the price range filter process.

  • Get the range value from the slider input.
  • Post price range to the server-side script (fetchProducts.php) via Ajax using jQuery.
  • Display filtered product data under the productContainer div.
<script>
function filterProducts() {
    var price_range = $('#price_range').val();
    $.ajax({
        type: 'POST',
        url: 'fetchProducts.php',
        data:'price_range='+price_range,
        beforeSend: function () {
            $('.wrapper').css("opacity", ".5");
        },
        success: function (html) {
            $('#productContainer').html(html);
            $('.wrapper').css("opacity", "");
        }
    });
}
</script>

Filter Products by Price Range with PHP (fetchProducts.php)

The fetchProducts.php file is loaded by the Ajax request of the filterProducts() function at the client-side script.

  • Fetch records from the database based on the selected price range using PHP and MySQL.
  • Build an HTML list with the filtered product data.
  • Return the product list to the Ajax success method in HTML format.
<?php 
if(isset($_POST['price_range'])){
    
    
// Include database configuration file
    
include "dbConfig.php";
    
    
// Set conditions for filter by price range
    
$whereSQL '';
    
$priceRange $_POST['price_range'];
    if(!empty(
$priceRange)){
        
$priceRangeArr explode(','$priceRange);
        
$whereSQL "WHERE price BETWEEN '".$priceRangeArr[0]."' AND '".$priceRangeArr[1]."'";
        
$orderSQL " ORDER BY price ASC ";
    }else{
        
$orderSQL " ORDER BY created DESC ";
    }
    
    
// Fetch matched records from database
    
$query $db->query("SELECT * FROM products $whereSQL $orderSQL");
    
    if(
$query->num_rows 0){
        while(
$row $query->fetch_assoc()){
    
?>
        <div class="list-item">
            <h2><?php echo $row["name"]; ?></h2>
            <h4>Price: $<?php echo $row["price"]; ?></h4>
        </div>
    <?php 
        
}
    }else{
        echo 
'<p>Product(s) not found...</p>';
    }
}
?>

Conclusion

This example script makes it easy to integrate the price range slider filter into the products list. Not only the product list, but also you can add a range filter feature to any data list in PHP using jQuery. The range slider design can be customized as per the webpage layout by modifying the jquery.range.css file.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Paco Ramon Said...

Leave a reply

keyboard_double_arrow_up