I want to call a function after a form is submitted, I see we can do this in jQuery with .submit(handler function()) but the method description says, the handler method will be executed just before the form is submitted. How can I actually attain this? Should I use setTimeout after the form is submitted or is there any other solution for this?
4 Answers
$("#myFormId").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: $(this).prop('method'),
url : $(this).prop('action'),
data: $(this).serialize()
}).done(function() {
doYourStuff();
});
});
3 Comments
Mihai
That's not calling the function "after" the form is submited
Mihai
Not to mention that the submit might fail and you only want to execute MyfunctionCall() only if the submit was successful
adeneo
Did'nt read the question well enough, but doing something after the form is submitted is only possible with ajax, and the form submit failing is'nt really part of the question.
You could use plugin http://www.malsup.com/jquery/form/#ajaxSubmit and do what ever you need on the callback method success
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
success: function() {
// callback code here
}
};
// bind to the form's submit event
$('#myForm2').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
Comments
Flow:
- window.sessionStorage['submit'] is initially an empty string.
- once you type something in the textbox, and click the submit button, the value in the textbox is saved to window.sessionStorage['submit']. That means the window.sessionStorage['submit'] is not empty anymore. it containes a value.
- the page refreshes after you submit the form.
- the onload function will check if there is anything in window.sessionStorage['submit']. if its not empty it means that the form was submitted by a user. then it reset the window.sessionStorage['submit'] to empty string again.
Its using Session Storage which is supported in all the major browsers.
<html>
<body onload="checkSubmitStatus()">
<form name="text" action="">
<input type="text" id="txtId">
<input type="submit" value="submit" onclick="storeInSession()"/>
</form>
<script type="text/javascript">
function storeInSession(){
window.sessionStorage['submit'] = document.getElementById('txtId').value;
}
function checkSubmitStatus(){
if(window.sessionStorage['submit']){
alert('The form was submitted by '+ window.sessionStorage['submit']);
window.sessionStorage['submit'] = '';
}
}
</script>
</body>
2 Comments
Annapoorni D
Sorry I don't get how this lets me know if the form is submitted.
Annapoorni D
thank you for the explanation let me try and see. If I am not able to achieve I have to go in for Barmer's suggestion of submitting the form via ajax.
submit(), submit the form yourself (using ajax) and then run what you wanted to execute after form submission