I've added a hook to form submit event (there are other events on the form submit ) and need to report the submit to a server on another domain using createlement(script).
How can I cause the submit function to wait to make sure the createlement(script) has successfully accessed the server ?
I've added a hook to form submit event (there are other events on the form submit ) and need to report the submit to a server on another domain using createlement(script).
How can I cause the submit function to wait to make sure the createlement(script) has successfully accessed the server ?
Share Improve this question edited Dec 22, 2010 at 12:12 Shervin Asgari 24.5k32 gold badges108 silver badges144 bronze badges asked Dec 22, 2010 at 11:47 NirNir 25.4k26 gold badges84 silver badges120 bronze badges 03 Answers
Reset to default 6How about something like this:
<script>
function handleSubmit(form) {
doSomethingAsynchron(
function() { // callback function
form.submit();
}
);
return false;
}
</script>
<form onsubmit="return handleSubmit(this);" ... >
...
</form>
Try to make use of JavaScript events. You can register any function to be called when a certain event occurs. Either utilise some of the predefined events to signal the pletion of your code or use something like some Yahoo! library to create custom events which could represent the pletion of the server request (found the last one with a short Google search, but looks promising).
I expected JS to have a built-in custom event architecture but obviously it has not. Thus you need to use external libraries like this Yahoo! thing. Maybe this changes in the near future. This is above my knowledge. But I can surely remend using events because they solve exactly the problem you described.
(Alternatively you can do busy wait like Thariama described. Either with sleep cycles or not busy waiting in general is discouraged where possible.)
Illustration:
<script>
// register function b() for custom event
function a() {
//upload
// (takes time... but no busy wait)
//fire custom event
}
function b() {
//do some other code
}
</script>
<body>
<form onsubmit="a()">
</form>
</body>
A not very elegant solution would be to use a time interval to check if the script to has acsessed the server (check the response). For this use setInterval.