Predictive search results: Jquery run function after getJSON completes within keyup function

StackOverflow https://stackoverflow.com//questions/22056911

  •  22-12-2019
  •  | 
  •  

Question

I have been reading a lot of answers on here about deferred techniques on getJSON/ajax requests but nothing seems to fit my scenario. I am making a search input return a set of results based on a getJSON call after 4 characters. This is to limit the amount of results returned, and also the amount of ajax requests (open to more effective solutions).

search_input.on('keyup', function() {

    var string       = $(this).val();
    var quiet_chars  = 4;

    if(string.length < quiet_chars) {

        // Simple notifications function which passes a message to a div, and optional class
        notification('Type '+(quiet_chars - string.length)+' more characters to search');
    }
    if(string.length == quiet_chars) {
        notification('Searching...', 'loading');
        $.getJSON('stores/stores-search/'+string, function(data) {

            // Loop through data and build list....
            $('.search_results').html('<ul>'+list_html+'</ul>');

            // Function which shows/hides list items based on Jquery :contains
            searchResults(string);

        });
    }
    if(string.length > quiet_chars) {
        searchResults(string);
    }

});

The specific problem I am facing is if you quickly type in 5 (more than 4) characters, the if(string.length > quiet_chars) condition is met before $('.search_results').html('<ul>'+list_html+'</ul>'); has executed, and tells the user there are no search results.

I need to meet the if(string.length > quiet_chars) condition to continue filtering the returned results, but only after the list has been appended to the DOM from the getJSON request. Thanks.

Was it helpful?

Solution 2

Got it working!

var json_success = false,
    ajax_term;

function searchJson(string) {
    ajax_term = string;
    notification('Searching...', 'loading');
    $.getJSON('stores/stores-search/'+string, function(data) {

        // Loop through data and build list....
        $('.search_results').html('<ul>'+list_html+'</ul>');
        searchResults(string);
        json_success = true; 

    });
}

search_input.on('keyup', function() {

    var string       = $(this).val();
    var quiet_chars  = 4;

    if(string.length < quiet_chars) {
        json_success = false;
        notification('Type '+(quiet_chars - string.length)+' more characters to search');
    } else {

        if(json_success !== false || string.substr(0,4) !== ajax_term) {
            $.when(searchJson(string)).then(searchResults(string))
        } else {
            searchResults(string)
        }
    }
});

From here: https://stackoverflow.com/questions/5280699#5291067

If anyone is trying to get something similar working, here is my search results function:

//extends :contains to be case insensitive
$.extend($.expr[':'], {
    'containsi': function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

// Instant search results
function searchResults(searchTerm) {

    var searchSplit = searchTerm.replace(/ /g, "'):containsi('");

    $(".search_results .tile").not(":containsi('" + searchSplit + "')").each(function() {
        $(this).addClass('hide').removeClass('show');
    });
    $(".search_results .tile:containsi('" + searchSplit + "')").each(function() {
        $(this).removeClass('hide').addClass('show');
    });

    var resultCount = $('.search_results .show').length;

    if(resultCount != '0') {
        notification('Showing '+resultCount+' results');
    } else {
        notification('No results', 'error');
    }
}

Credit for the case-insensitive version of :contains goes to Rob Sawyer.

OTHER TIPS

edited to fit your specifications

bool dataLoaded = false; //this is a global variable we have outside of the scope of the search_input.on function
search_input.on('keyup', function() {

    var string       = $(this).val();
    var quiet_chars  = 4;

    if(string.length < quiet_chars) {
        //let's reset the dataLoaded flag if the user ends up deleting characters and what not
        if(dataLoaded)
           dataLoaded = !dataLoaded;
        // Simple notifications function which passes a message to a div, and optional class
        notification('Type '+(quiet_chars - string.length)+' more characters to search');
    }
    if(string.length == quiet_chars) {
        notification('Searching...', 'loading');
        $.getJSON('stores/stores-search/'+string, function(data) {

            // Loop through data and build list....
            $('.search_results').html('<ul>'+list_html+'</ul>');
            dataLoaded = true;
            // Function which shows/hides list items based on Jquery :contains
            searchResults(string);

        });
    }
    else if(dataLoaded){
        searchResults(string);
    }


});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top