最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending an Ajax request before form submit - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 19

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>

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>
发布评论

评论列表(0)

  1. 暂无评论