Dynamic Search with JSON - PHP - MYSQL

4

I've been searching the internet but I could not find any references, perhaps because I was searching wrong, so I resorted to creating this post.

I have a query in the database (MySql with PHP) that returns me a list of products with several characteristics (name, value, category, type, composition, etc.), and this listing is shown to the user on the screen.

On the left side we have filters, which are these features of the products listed initially, you would like:

1 - When selecting a filter, the result of the search is redone taking into account that selected filter, BUT WITHOUT GOING TO SEARCH THE INFORMATION AGAIN IN THE DATABASE, ie work with the result that is already in the screen of the user.

I know that for this it is necessary to create a JSON object and manipulate the information that is inside it, according to the filters that are selected, but to convert the result from PHP to the JSON object without problems (json_enconde / json_decode), but the problem is like searching within this object in order to show results with filters.

I do not want to fetch the information back into the database because if it does, I will have many queries and the response time can be high for the user.

If someone has any light to help, or has already made some similar code and can help me thank you.

Thanks to everyone

    
asked by anonymous 08.12.2014 / 20:43

1 answer

3

This can be done in different ways. Here is an example:

var restaurants = [{"name": "McDonald's"}, { "name": "KFC" }, { "name": "Pizza Hut" }, { "name": "Dominos" }, { "name": "Popeyes" }];

function mostrar(arr) {
    var lista = $('#lista'); // coloquei em cache aqui para não ter $('#lista').append() dentro do loop
    lista.html(''); // para limpar antes de voltar a colocar a lista

    arr.forEach(function (rest) {
        lista.append('<div>' + rest.name + '</div>');
    });
}
$('#busca').on('keyup', function () {
    var busca = this.value;
    var filtrados = restaurants.filter(function (rest) {
        return rest.name.toLowerCase().indexOf(busca) != -1;
    });
     mostrar(filtrados);
});
mostrar(restaurants); // para iniciar
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Escrevaumaletradeumdosnomesparafiltrar...<inputtype="text" id="busca" />
<div id="lista"></div>

This code looks for keyup to detect user input. It could be a click on a div too. Then it compares the value of the input with all the objects in the array and removes the ones that do not have that letter / word in the name. Ai calls the function to show the results by passing the array already filtered.

    
08.12.2014 / 21:02