Is it possible to send an ajax request in onsubmit() of a form? I have been trying it and the results are flaky, mainly because probably if the browser happens to take longer sending my request than it takes sending the original form, my request is discarded as soon as the location of the loaded page change, so sometimes it never even hits the server.
Basically, what I want to do is add an audit log collector that collects login events, I want to hook that to existing apps with minimal invasion.
Is it possible to send an ajax request in onsubmit() of a form? I have been trying it and the results are flaky, mainly because probably if the browser happens to take longer sending my request than it takes sending the original form, my request is discarded as soon as the location of the loaded page change, so sometimes it never even hits the server.
Basically, what I want to do is add an audit log collector that collects login events, I want to hook that to existing apps with minimal invasion.
Share Improve this question asked Aug 11, 2009 at 23:27 shipmastershipmaster 3,9744 gold badges31 silver badges33 bronze badges 1- If you're using a specific JavaScript framework for the AJAX request, let me know and I can give you a more specific answer. – James Skidmore Commented Aug 11, 2009 at 23:35
3 Answers
Reset to default 19This is easily achievable. Just hold off the form submission until the AJAX request completes.
Make your form onsubmit
attribute call the AJAX function and return false (which cancels the form submission). When your AJAX call completes, submit the form programmatically.
For instance:
<form name="myform" onsubmit="javascript: startAjax(); return false;">
...
<script type="text/javascript">
function startAjax() {} // Calls ajaxComplete() when finished
function ajaxComplete()
{
document.myform.submit();
}
</script>
There is another way to solve this issue, that is you can make the ajax call as synchronous.
Example:
xmlhttp.open("GET", imageUrlClickStream, false);
By this we can make sure that the form submission will wait until the ajax call get the response.
Replace onsubmit with onclick it work well for me because onsubmit going in loop.
<form name="myform" onclick="javascript: startAjax(); return false;">
...
<script type="text/javascript">
function startAjax() {} // Calls ajaxComplete() when finished
function ajaxComplete()
{
document.myform.submit();
}
</script>