Filtering and Sorting page

Viewed 52

i made a page that shows a list of accounts with details (7700 accounts) and then i add pagination and filters. when user submit his filters , filters send in body of my api and get back the new and filtered data. its ok but when user change the page and go to page 2 from first page , the all filters will disappear. how can i fix the filter even if the user change the pages

$('#pagination-demo').twbsPagination({
    totalPages: 270,
    visiblePages: 10,
    next: 'Next',
    prev: 'Prev',
    onPageClick: function (event, page) {
        console.log(page)

        ///////////////////////showing table information///////////////////
        let FilterList = {
            business_type: "",
            influencer_size: "",
            avg_likes: "",
            avg_comments: "",
            eng: "",
            gender: "",
            avg_post_price: "",
            avg_story_price: ""
        }

        let bodyContent = new FormData();
        let data = new FormData();
        data.append("page", page);
        data.append("filter", JSON.stringify(FilterList));

        /////////////////requesting and geting data//////////////

        ////////////////filters////////////////////

        var showAllResult = document.getElementById("showAllResult")
        showAllResult.addEventListener('click', () => {
            var CopyOfFilterList = [...FilterList]

            //////////////new request to send filter and geting response////////
        })
        $('#page-content').text('Page ' + page) + ' content here';
    }
});
1 Answers

As when you change the page, the page is refreshed all the data inside the variable is gone. And filter list variable is set to its initial state.

You can pass the query to the url. You can use URLSearchParams in javascript to pass the filters as a query params.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

I am not sure how the url is change in your code, but following is an example for change the queries in the url:

const filters = {
  business_type : "technology" ,
  influencer_size : "5",
  avg_likes : "1000" ,
  avg_comments : "6" ,
  eng : "" ,
  gender : "" ,
  avg_post_price : "200" ,
  avg_story_price : ""
}

let queryParams = new URLSearchParams(window.location.search)

for (const key in filters) {
    if (filters[key]) queryParams.append(key, filters[key])
}

history.replaceState(null, null, "?"+ queryParams.toString());

If you want to get the value from the url query as an object you can use

Object.fromEntries(queryParams.entries())

This will get you the values as an object. You can explore more on mozilla documentation. Hope this helps!

Related