Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 860
shipmaster Avatar asked Aug 11 '09 23:08

shipmaster


People also ask

How would you make an AJAX call to submit a form?

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.

What is before send in AJAX?

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.

How do I send an AJAX request after some time?

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.

What is the difference between AJAX and form submit?

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.


1 Answers

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>
like image 138
James Skidmore Avatar answered Sep 24 '22 20:09

James Skidmore