I’ve been doing a lot of AJAX work recently and noticed that sometimes, when doing AJAX calls on key up or key down, the results returned don’t always reflect the query. This is the case when there are multiple AJAX requests occuring at the same time. If they complete out of order, the updated results can often be confusing.
For example:
I have the following JSON dataset:
{ “name” : “smatt” , “name” : “smoke”, “name” : “smith” , “name” : “smith2″ …etc }
This data is stored off-site and has a lag time when getting returned ( This, most likely, would not be the case with a small predefined dataset like the one above, but would very possibly happen with database queries ). As I type ‘s’, a query is sent out (‘s’); ‘m’ adds another query (‘sm’); ‘i’ adds another (‘smi’)…etc.
If my ‘smi’ query is returned before my ‘s’ query, then my results for ‘smi’ will be overwritten by my results for ‘s’, returning “smatt” “smoke” “smith”… when what I should be getting back is a list of all the “smith”s. A simple way to check this is to add an additional “if” statement on success. Example:
function query(input_string_from_field)
{
var url = "getdata.php?q="+input_string_from_field;
$.getJSON(url, function(data){
//This runs the check to make sure you are returning
//the correct data
if(input_string_from_field == $('#input_field_ID').val())
{
//display results
}
});
}
By adding:
if(input_string_from_field == $('#input_field_ID').val())
we check to make sure that the last thing that the user typed is the query for the data that is being returned. If it isn’t, the data isn’t displayed. If it is, show the data.