Search code examples
javascriptajaxjsonlawnchair

How to perform a WHERE LIKE "%string%" search equivalent for JSON in lawnchair


When the website is loaded I want to do one ajax call to a PHP script that returns a json array of data (max 200 pieces), and store it in lawnchair. See http://brian.io/lawnchair/

I preload the data to not have to wait every time for PHP/MySQL to answer the ajax request. I want an autocomplete field that returns values while typing. The result comes from lawnchair so no more calls are made to the MySQL server.

So consider we have this dataset:

When the user types "p", all of the above needs to be shown. When the user types "app" only Apple and Pineapple are shown.

Thus I need to search through the dataset with a MySQL WHERE LIKE "%string%" equivalent code. I have looked on Brian's website website, but I see only exact match searches possible with query? See: http://brian.io/lawnchair/plugins/

Thanks in advance for any hint in the right direction.


Solution

  • A quick glance at the (relatively poor) documentation suggests, that the following would work:

    var hits = [],
        searchExpr = RegExp.escape(searchValue);
    
    fruitStorage.where('/' + searchExpr + '/i.test(record.name)', function (record) {
        hits.push(record);
    });
    
    // now do something with hits
    

    Without looking deeper into the source code, this might work as well.

    var hits = [],
        searchExpr = new RegExp(RegExp.escape(searchValue), "i");
    
    fruitStorage.where(
        function (record) { return searchExpr.test(record.name); }, 
        function (record) { hits.push(record); }
    );
    

    BTW, RegExp.escape() is taken from this answer.