keyup event as this will put unnecessary load on your server. Instead, the thing to do is to wait a little while after the user's last key release to see if she's stopped typing before firing off a request.
I'm sure that there are hundreds of code snippets lying about for doing just this, and that JQuery probably already has something built in or a plugin for it, but a quick Google search didn't turn up anything for me so here I am, sharing my simple solution for delayed Ajax validation in JavaScript.
// A simple mechanism to handle delayed validation based on keyboard entry. // Copyright (c) 2008, Aral Balkan, All Rights Reserved. // Released under the MIT license. validationFunctionRefs = []; timers = []; function callAfterDelay(fnRef, duration){ // Check if a timer for this validation function is already in effect // and reset it if it is. for (i = 0; i < validationFunctionRefs.length; i++) { fnToCheck = validationFunctionRefs[i]; if (fnToCheck == fnRef){ timer = timers[i]; clearInterval(timer); timers.splice(i,1); validationFunctionRefs.splice(i,1); break; } } timer = setTimeout(fnRef, duration); timers.push(timer); validationFunctionRefs.push(fnRef); return timer }
To use it, simply call callAfterDelay from your event handler for the keyup event. e.g., in JQuery:
$("#id_vat_no").keyup(function(){callAfterDelay(checkVatNumber, 500)})
In this case, 500ms after the user stops typing in a text input, the checkVatNumber method will make a JSONP call to the European VAT Number Validation service to see if the entered VAT number is valid.
The Delaying Ajax-based validation triggers article by Aral Balkan, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial 2.0 UK: England License.
*effect, not affect
Wow, someone actually reads the comments! :) Thanks, Evert — fixed.
Nice snippet – thanks.
I haven’t tried it as yet, but don’t you also need to splice out the existing reference to the function from validationFunctionRefs, otherwise you’re gonna end up with two references to the function in the validationFunctionRefs array, but only one timer in the timers array.
Hey Toby,
You’re right, of course, I just updated the script. Thanks for catching it.
Good stuff mate – I’m going down the same Flex / Django / GAE route at the moment, and these posts are all pretty interesting for me as an old Flash person trying to get to grips with a few other technologies. Keep up the good work Sir.
how can i use it to execute ajax requests when user stops typing.
THANKS!!!!
Ajax-lite here. This really helps me out a lot. Thank you very much!