jQuery: submit form via Ajax with jQuery Form Plugin
January 16, 2012 19:32:20 Last update: January 16, 2012 19:32:54
You can submit a form via Ajax by the jQuery Form Plugin. There are two main methods:
jQuery Form Plugin is not in the core jQuery API, so you have to include an additional JS file:
-
ajaxForm: prepares a form for Ajax submit.
Example:$('#myFormId').ajaxForm({ target: '#output1', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback // other available options: //url: url // override for form's 'action' attribute //type: type // 'get' or 'post', override for form's 'method' attribute //dataType: null // 'xml', 'script', or 'json' (expected server response type) //clearForm: true // clear all form fields after successful submit //resetForm: true // reset the form after successful submit // $.ajax options can be used here too, for example: //timeout: 3000 } );
When the form is submitted, it is sent via Ajax. -
ajaxSubmit: submit a form via Ajax.
Example:$('#myForm2').submit(function() { // inside event callbacks 'this' is the DOM element so we first // wrap it in a jQuery object and then invoke ajaxSubmit $(this).ajaxSubmit({ target: '#output2', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback // other available options: //url: url // override for form's 'action' attribute //type: type // 'get' or 'post', override for form's 'method' attribute //dataType: null // 'xml', 'script', or 'json' (expected server response type) //clearForm: true // clear all form fields after successful submit //resetForm: true // reset the form after successful submit // $.ajax options can be used here too, for example: //timeout: 3000 }); // !!! Important !!! // always return false to prevent standard browser submit and page navigation return false; });
jQuery Form Plugin is not in the core jQuery API, so you have to include an additional JS file:
<head> <script type="text/javascript" src="jquery-1.3.2.js"></script> <script type="text/javascript" src="jquery.form.js"></script> </head>