DEV Community

Shubham Raturi
Shubham Raturi

Posted on

Add Multiple Filter using one function in jQuery, Ajax

Most beginners when they need a filter in a website create multiple functions for each filter, for example, price filter, date-range filter, tag filter, and category filter.
We can create a multiple filters using a single function
below we have a code example.

Creating a predefined variable for all filters

function filter(price,page=1, perPage=2,){
let data = {price,page,perPage}; // set your JSON stringify data to be post.
   $.ajax({
  url: "ajax_url", // your ajax URL
  cache: false, 
  data: data, // Your post data
  method: post // Method
  success: function(data){
   // do filter with response to html or variable.
  }
});
}
Enter fullscreen mode Exit fullscreen mode

In this senerio i have setup a default values and i can run this function in which button i want to call. EX:

$("#price_filter").click(function(){
let price = $("#price").val();
filter(price);
})
Enter fullscreen mode Exit fullscreen mode

This is just an example of an Argument: An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The above example has a function with three argument,price, page and perPage

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay