I have an AJAX form that I need to submit every time a user types something in a textbox.
The following code works:
<% using (Ajax.BeginForm("myAction", "myController", null, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "resultDiv" }, new { id = "myForm" }))
{%>
<script type="text/javascript" language="javascript">
jQuery("#myForm").keyup(function() { $('#myForm').trigger('onsubmit'); });
</script>
Search: <input type="text" id="myTextField" />
<%} %>
I've been trying to update the code so that there is a delay of 1sec in submitting the form. The delay would allow for the form to be submitted only when the user stops typing for the one second interval. This code does not work:
<% using (Ajax.BeginForm("myAction", "myController", null, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "resultDiv" }, new { id = "myForm" }))
{%>
<script type="text/javascript" language="javascript">
var timerid;
jQuery("#myForm").keyup(function() {
clearTimeout(timerid);
timerid = setTimeout(function() { $('#myForm').trigger('onsubmit'); }, 1000);
});
</script>
Search: <input type="text" id="myTextField" />
<%} %>
Any suggestions on how to delay the ajax form from being submitted until a user stops typing for a short period of time?
UPDATE: Using Chrome, I found that the script stops somewhere in MicrosoftAjax.js in a caught exception. I don't know how to find what the exception is exactly.
For debugging purposes, I rewrote the code as follows:
var timerid;
jQuery("#myForm").keyup(submitWithTimeout);
function submitWithTimeout() {
clearTimeout(timerid);
timerid = setTimeout(submitAjaxForm, 2000);
}
function submitAjaxForm() {
$('#myForm').trigger('onsubmit');
}
The code executes both lines in "submitWithTimeout" function, and accurately waits for 2 secs. It reaches the submitAjaxForm function, and stops at a caught exception in MicrosoftAjax.js file, as mentioned before.
UPDATE 2: I am now using the debug version of MicrosoftAjax.js and found the source of the error. Using the expression watcher in Chrome, I was able to narrow it down to the following issue: the "eventObject" variable is null while MicrosoftAjax.js is executing. What I gather from the source code is that the onsubmit code's "event" is null when using the timer to submit the form. Any ideas why?
<form action="myAction" id="myForm" method="post" onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'myResult' });">
The new Sys.UI.DomEvent(event)
has a null value for the "event" parameter when using the timeout method.