Reputation: 849
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?
Upvotes: 7
Views: 30361
Reputation: 1033
Cancel the form submit event, then invoke the form submit manually and then execute your function..
Upvotes: 0
Reputation: 12683
Flow:
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>
Upvotes: 0
Reputation: 318182
$("#myFormId").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: $(this).prop('method'),
url : $(this).prop('action'),
data: $(this).serialize()
}).done(function() {
doYourStuff();
});
});
Upvotes: 6
Reputation: 2760
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;
});
});
Upvotes: 0