How to create a Filter system(sending filter words to the back-end)

Hello there,

I would like to create a filter system were I have to send the filter words back to the Back-end so it can filter there. but how do i send that data to the back-end?

I understand that i have to use fetch for that or in my case axios since im using React.
what http type would be the best for that and how do i code that?

I know when I use have to look up a single product we can use the GET method with a id at the end of the url.

but how do we achive that with multiple filter words like: TitleName, PriceMin, PriceMax??

can anybody help me with this?

Thanks in advance

but how do i send that data to the back-end?

Like you said, with fetch or some other tool.

I understand that i have to use fetch for that or in my case axios since im using React.

I’ve used both with React, I’ve used both when not using React. I know of no reason why you couldn’t use fetch with React - that is actually what I usually use. If you want to use axios, that’s fine, but not because you have to.

what http type would be the best for that and how do i code that?

Remember that the names of the methods and what they are associated with are just arbitrary. (I once had an interview where they asked me if I could delete a record with a GET request. I told them that it might be confusing to the next coder, but it could be done. They were relieved to hear that as they said 90% of the people said it could only be done with a DELETE request. I still didn’t get the job.)

So, semantically, a GET makes the most sense - you can pass in parameters with that and you are doing what GET is made to do - retrieve information. The only exception would be if there is a lot of information that needs to be passed (like if you didn’t need to pass the search words but the entire text) - one of the disadvantages of GET is that you can’t pass a body. In cases like that, I’ve seen people use POST when really what they’re doing would make more sense with GET.

I know when I use have to look up a single product we can use the GET method with a id at the end of the url.

You can send anything thing you want in a GET request url, in one or many parameters, and any data that can be serialized into a URL friendly string.

but how do we achive that with multiple filter words like: TitleName, PriceMin, PriceMax??

There are a lot of ways to do this. The simplest would be something like:

https://www.myserver.com?titlename=apple-jacks&pricemin=12.34&pricemax=23.45

Or if you want, you can put them all in an object, stringify that object, and then base 64 encode it and just send it as:

https://www.myserver.com?params=Ba5364EnC0dEd5tr1ng

That is easy to do and easy to decode in the server.

Does that all make sense? There may be some other possibilities , but that is an approach.

2 Likes

I should also note that the base 64 encoding may be a little extreme - there are also functions like encodeURI and encodeURIComponent. It really depends on what you need.

That makes perfect sense I have seen that on many web shops.
Thanks

I am trying to get it to work but im not sure if i am doing it correct
i am getting a 405 error

    async getFilteredProducts() {
        const TitleFIlter = document.getElementById("TitleFIlter").value;
        const PriceFIlter = document.getElementById("PriceMin").value;
        const descriptionFilter = document.getElementById("DescriptionFilter").value

        const url = `api/products/${TitleFIlter}/${descriptionFilter}`     

        const response = await axios.get(url)
        const data = await response.data;
        this.setState({
            allproducts: data,
        });
        console.log(data);
    }

My server is like this:

[HttpGet("{Title}/{description}")]

I think a 405 means that the method exists, but you aren’t allowed.

There should be a response with more information. What is that? But ultimately it’s going to depend on how the server is set up.

I think i understand why i get the error:

error that i get:
https://localhost:44340/api/upload/y/ 405
C:16 Uncaught (in promise) Error: Request failed with status code 405

So in my server I have this code:

		[HttpGet]
		[Route("{Title}/{Description}")]
		public async Task<List<Product>> GetFilter(
			[FromQuery] string Title,
			[FromQuery]  string Description)
		{
			IQueryable<Product> products = _context.products;

		if (!string.IsNullOrEmpty(Title))
				products = products.Where(x => x.Title.ToLower().Contains(Title.ToLower()));

			if (!string.IsNullOrEmpty(Description))
				products = products.Where(x => x.Description.ToLower().Contains(Description.ToLower()));

			return await products.ToListAsync();
		}

the server expects 2 parameters Title and Description

but when i only fill in one search field, react only returns a url with one parameter

what would be a proffesional way to solve this?

and is it normal for a website show all search results
even when only one search -word/filter-input is used ?

The way that works? Can the frontend send an empty string if other field isn’t filled?

and is it normal for a website show all search results
even when only one search -word/filter-input is used ?

I’m not sure I understand the question. If you mean, “if someone does a filtered search and they get back 374 responses, should I show them all.” then it depends.

You can send them all and have some kind of frontend pagination so you don’t have all those elements on the screen. Another option is backend pagination. It sends you “page 1” which is the first 20 (or whatever) responses and then you request “page 2” when you need it.

Im sorry that im not clear what i mean is that:
lets say i have 4 search options: title, price, description and quantity
so that url would be something like:
myserver,com?title=apple&price=20&description=cheese&quanty=5

but what if i only search on TItle does that url need to look like this?
myserver,com?title=apple&price=&description=&quanty=

i would be better if it would only show up like this:
myserver,com?title=apple

how do i achive something like that because the backend expects 4 perameters.
because when the other peramets are empty the url will only return 1 perameters
and i will crash again.

I eon’t know how your servers are working - I don’t do that language. But I imagine there is a way that the shorter solution would work, those values just coming in as null or whatever. There may be a néed to avoid a null pointer exception, but I would guess that it’s pretty easy.

btw this way of placing parameters in the url is called query. You might wanna look at the API’s and Microservices curriculum, section Basic Node and Express. The few challenges in the end has some words regarding the different methods a server can receive data, starting with Get Route Parameter Input from the Client.
You dont have to put additional empty parameters in the ulr, omitting them will simply return undefined when the back end looks for them and the server should simply be made to handle those, like assigning them an empty value, or simply placing one filter on the search. If you are searching a database, it can be as simple as including just one parameter in the search command(if there was one parameter sent by the user)

i have finally found the solution :grinning_face_with_smiling_eyes:
it was defnenitly a problem that has to do with the back-end coding
it was just as simple as

[HttpGet]
		[Route("{Title?}/{Description?}")]

Just a “?” after each parameter in the Route to make them optional

Im sorry but thank you very much

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