Filter JSON records by Javascript or PHP

Asked

Viewed 162 times

1

I have a question about how to filter data when the customer fills in an input field. I am searching all server records (running PHP) through a jQuery JSON request and would like to know how to make a less "restrictive" filter by Javascript, since the index() method returns only records referring to precisely typed values, but when I perform the search directly by query the result is closer than needed. I don’t want to use comic books too often for performance reasons.

Follow the javascript code (where I take the value entered by the user, and filter the JSON records):

if( value.nome_produto.indexOf(busca) != -1 ){
    tr += `<tr class='_item_em_falta _tr_relative'>
        <td> ${value.registro} </td>
        <td> 
            <a href='detalhe.php?codigo=${value.produto_id}'>
                <img class='_minha_img' src='${value.imagem_pequeno}'>
            </a>
        </td>
        <td>
            <a href='detalhe.php?codigo=${value.produto_id}'>
                ${value.nome_produto}
            </a>
        </td>
        <td> ${value.preco_produto} </td>
        <td> ${value.origem_produto} </td>
        <td> ${value.quantidade_total} </td>
        <td> ${value.quantidade_vendida} </td>
    </tr>`;

the index filter() used above only returns the products with identical name to the one entered by the user (Case Sensitive and etc). would like to use a way to filter the data in a less restrictive way (like the LIKE %example% command in Mysql)

  • I request to make a few more edits to your question. Add less "restrictive" filter examples and also put code you have made.

1 answer

0

The LIKE of Mysql and the indexOf of PHP do a very similar type of search. What you can do to solve your Case Sensitive in javascript, equals values. Ex:

var v1 = value.nome_produto.toUpperCase();
var v2 = busca.toUpperCase();

if( v1.indexOf(v2) != -1 ){
    tr += `<tr class='_item_em_falta _tr_relative'>
        <td> ${value.registro} </td>
        <td> 
            <a href='detalhe.php?codigo=${value.produto_id}'>
                <img class='_minha_img' src='${value.imagem_pequeno}'>
            </a>
        </td>
        <td>
            <a href='detalhe.php?codigo=${value.produto_id}'>
                ${value.nome_produto}
            </a>
        </td>
        <td> ${value.preco_produto} </td>
        <td> ${value.origem_produto} </td>
        <td> ${value.quantidade_total} </td>
        <td> ${value.quantidade_vendida} </td>
    </tr>`;

With this it will return true for a comparison like: test == TEST!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.