I am using $(function() {}); to run jQuery events on page load.
I have a data filtering form that uses 3 input elements to filter data by keywords (year, make, model). All three have the same class, to which I assign an .on("keyup") handler which submits the (one or two or three) values entered to a PHP script, which returns json.
Problem: after typing input, the results are filtered as expected, however a moment later, the results are loaded again, but this time as if the page had just loaded (all results).
Here is some of the code:
function load_vehicle_fitment(args) {
if(args === undefined) {
args = {};
}
args['func'] = 'print_fitment';
$.get('ajax_get.php', args,
function(data) {
$('#fitment_data').html(data.html);
}, "json");
}
$(function() {
// INITIAL
load_vehicle_fitment();
// FILTER YMM COMBOS
$(".filter_input").on("keyup", function(e) {
var typed_length = $(this).val().length;
if(typed_length < 1 || typed_length > 2) {
var args = {};
var year = $("#year").val();
var make = $("#make").val();
var model = $("#model").val();
if(year.length > 3) {
args["year"] = year;
}
if(make.length > 2) {
args["make"] = make;
}
if(model.length > 2) {
args["model"] = model;
}
load_vehicle_fitment(args);
}
});
});
What is causing this behavior??
UPDATE:
The search form:
<form name="vehicle_search" method="get" action="">
<input type="hidden" name="view" value="vehicles">
<input type="text" id="year" name="year" maxlength="4" size="2" class="filter_input" placeholder="Year" value="" style="padding: 3px;" autocomplete="off">
<input type="text" id="make" name="make" class="filter_input" placeholder="Make" value="" style="padding: 3px;">
<input type="text" id="model" name="model" class="filter_input" placeholder="Model" value="" style="padding: 3px;">
<input type="submit" value="Add" id="add_vehicle_button" disabled="disabled">
</form>
UPDATE:
@Kevin B, @teewuane
I have wrapped the jQuery request in a setTimeout, which basically makes it so that it “waits” until it has been n miliseconds after a keyup, at which point it runs. This saves http requests from this happening:
XHR finished loading: ".../ajax_get.php?year=1982&make=F".
XHR finished loading: ".../ajax_get.php?year=1982&make=Fo".
XHR finished loading: ".../ajax_get.php?year=1982&make=For".
XHR finished loading: ".../ajax_get.php?year=1982&make=Ford".
The funny thing is, this seems to have corrected the error I was experiencing. It hurts that I don’t know exactly why.
I wouldn’t go as far as abandoning on-keyup lookups, however you should at least throttle it and abort existing lookups when a new one is started.