Annapoorni D
Annapoorni D

Reputation: 849

Call a function after a form is submitted using JavaScript / jQuery

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

Answers (4)

nvkrj
nvkrj

Reputation: 1033

Cancel the form submit event, then invoke the form submit manually and then execute your function..

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Flow:

  1. window.sessionStorage['submit'] is initially an empty string.
  2. 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.
  3. the page refreshes after you submit the form.
  4. 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>

Upvotes: 0

adeneo
adeneo

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

Mihai
Mihai

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

Related Questions