Sprottenwels Sprottenwels - 2 months ago 7
jQuery Question

Make JSON available for later use

I am trying to build a simple autocomplete feature.

My first intention was to query a specific database with a

%like%
statement every time the user adds or deletes a character in an
<input>
, then displaying the result.

But I would like to prevent this heavy database usage by, for example, fetching a JSON and then using that.

How could I make that JSON file available to my jQuery script?

Answer

When you know that the results of your autocomplete lookup shouldn't change each time, you can cache the results into an object as described on the jQuery UI Autocomplete demo page:

$(function () {
    var cache = {};
    $("#birds").autocomplete({
        minLength: 2,
        source: function (request, response) {
            var term = request.term;
            if (term in cache) {
                response(cache[term]);
                return;
            }
            $.getJSON("search.php", request, function (data, status, xhr) {
                cache[term] = data;
                response(data);
            });
        }
    });
});

It sounds like you want to load the full JSON results up front before the user starts typing anything, though. In that case, simply load the JSON object up front like this when the page first loads:

$.getJSON("search.php", request, function (data, status, xhr) {
    cache[term] = data;
    response(data);
});

And then use the local object ("cache" in the example above) as the source for your autocomplete lookup (see the default and custom display autocomplete demos for your main options there), e.g., something like this:

$("#autocompleteInput").autocomplete({
    source: cache
});