When a user is inputting something, I need to check user input against the corresponding data in database using AJAX, but I can’t continuously check user input against the data in database because that would overwhelm my database server. I just want to start an AJAX request at a significant/obvious/sensible pause during user inputting. For example, the input cursor doesn’t move for one or two seconds.From the viewpoint of user, he thinks the check is real-time. How to do this using Jquery?
Why doesn’t my code work as expected?
function subjectivecheck(id){
alert(id);
var cost=(new Date().getTime() - start.getTime())/1000;
var value=$('#question'+id).val();
$.post("subjectivecheck.php?",{val:value, qid:id,time:cost, a_id:"<?php echo $announcementid; ?>"},function(xm){
switch(parseInt(xm)){
case 4:
{ $htm='Congrats,you have passed the test.';
$('#success').css({"color":"green"});
$('#success').text($htm);
return;
}
case 1:
{
$htm='V';
$('#sign'+id).css({"color":"green"});
$('#sign'+id).text($htm);
break;
}
case 0:{
$htm='X';
$('#sign'+id).css({"color":"red"});
$('#sign'+id).text($htm);
break;
}
case 3:{
$('#subjectivequestion').text('You have failed at this announcement.');
$('#choicequestions').text(" ");
}
}
});
}
var ajaxCallTimeoutID = null;
function subjectivecheckcallback(id){
if (ajaxCallTimeoutID != null)
clearTimeout(ajaxCallTimeoutID);
ajaxCallTimeoutID = setTimeout(subjectivecheck(id), 1000);
}
Basically, you want to initiate your AJAX call some time after the user’s last input. If you’re using a textbox, you can do this by handling the
keyupevent and scheduling your AJAX call usingsetTimeout(). At the start of your event handler, you can check for a scheduled call and cancel it (since the user started typing again):If you want to react to user input across the entire form, then you just have to expand the events your handler handles. You would probably want to handle
keyupfor text boxes, textareas and select elements,changefor select elements, and probablyfocuson everything.