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.
Answer: Use the jQuery $. post() Method You can simply use the $. post() method in combination with the serialize() method to submit a form using AJAX in jQuery. The serialize() method creates a URL encoded text string by serializing form values for submission. Only "successful controls" are serialized to the string.
The beforeSend function is a pre-request callback function that runs before the request is sent to the server. The beforeSend() function use to set the custom headers and all, it is an Ajax event that triggers before an Ajax request is started.
Use setInterval() when you want to send AJAX request at a particular interval every time and don't want to depend on the previous request is completed or not. But if you want to execute the AJAX when the previous one is completed then use the setTimeout() function.
A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With