shipmaster shipmaster - 3 months ago 7
HTML Question

Sending an Ajax request before form submit

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.


This 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()