shipmaster
shipmaster

Reputation: 3974

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.

Upvotes: 5

Views: 8958

Answers (3)

user2396233
user2396233

Reputation: 1

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>

Upvotes: 0

Chandra
Chandra

Reputation: 1307

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.

Upvotes: 0

James Skidmore
James Skidmore

Reputation: 50298

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()
{
  document.myform.submit();
}
</script>

Upvotes: 19

Related Questions