I have a simple form with remote=true.
This form is actually on an HTML Dialog, which gets closed as soon as the Submit button is clicked.
Now I need to make some changes on the main HTML page after the form gets submitted successfully.
I tried this using jQuery. But this doesn't ensure that the tasks get performed after some form of response of the form submission.
$("#myform").submit(function(event) {
// do the task here ..
});
How do I attach a callback, so that my code gets executed only after the form is successfully submitted? Is there any way to add some .success or .complete callback to the form?
I just did this -
And things worked perfectly .
See this api documentation for more specific details.
For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions
here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form
here is the callback referenced in the AjaxOptions
in the controller method for MVC it looks like this
I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.
You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.
But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:
preventDefault
method)First, you'll have to cancel the form submit action like so:
And then, grab the value of the data. Let's just assume you have one text box.
And then fire off a request. Let's just assume it's a POST request.
And this should about do it.
Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.
Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.
I do not believe there is a callback-function like the one you describe.
What is normal here is to do the alterations using some server-side language, like PHP.
In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.
PHP:
One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.
http://api.jquery.com/jQuery.post/