Waiting Until User Stops Typing to Check the Status Using Ajax

There are many cases when you have to check some status in the server side while the user is typing in the data. One example that comes to mind is the username check - you can check for the availability of the username when the user is keying in the name. Usually this is done on the 'onchange' event. It can be done on the 'keypress' event too - but not many people prefer that because its expensive. Fetching data from the server takes time. A better method is to wait until the user completes typing to check the data - I'll show you how to do that in this tutorial.

Examples

onChange Lookup

This is how the onchange event lookup works - you have to change the focus from the current field for the event to fire...

onKeypress Lookup

This is another option - but its expensive and often unnecessary

Lookup After Typing

This is the intended effect - it will only do the lookup after the user stops typing.

Code

function init() {
	key_count_global = 0; // Global variable
	document.getElementById("name_stop").onkeypress = function() {
		key_count_global++;
		setTimeout("lookup("+key_count_global+")", 1000);//Function will be called 1 second after user types anything. Feel free to change this value.
	}
}
window.onload = init; //or $(document).ready(init); - for jQuery

function lookup(key_count) {
	if(key_count == key_count_global) { // The control will reach this point 1 second after user stops typing.
		// Do the ajax lookup here.
		document.getElementById("status_stop").innerHTML = " ... lookup result ...";
	}
}

Explanation

The lookup function will be called 1 second(changeable in code) after the user hits a button - but since the ajax lookup is inside the 'if' condition, the ajax lookup will not happen. It will happen only after the user stops typing for 1 second.

This effect is achieved using 2 variable which holds essentially the same data - but at different times. First variable is the 'key_count_global' variable - which as its name suggest is a global variable. The other variable is 'key_count' - which is passed by value to the function - after one second. The lookup will be done only after both variables have the same value - that will only happen if the user stops typing for 1 second.

I like to keep the lookup delay at 1 second - but if your users are slow typers, you can increase the value as you like.

blog comments powered by Disqus