HTML
First, we load jquery library and jquery.form.js plugins. Then we go to the HTML part.
jquery.form.js plugin official website address: http: //www.malsup.com/jquery/form/
<div class="demo">
<form id="my_form" action="submit.php" method="post">
<p>Name: <input type="text" name="uname" id="uname" class="input"></p>
<p>Sex: <input type="radio" name="sex" value="1" checked> Man <input type="radio" name="sex" value="2"> Female </p>
<p>Age: <input type="text" name="age" id="age" class="input" style="width:50px"></p>
<p style="margin-left:30px"><input type="submit" class="btn" value="Submit"><span id="msg"></span></p>
</form>
<div id="output"></div>
</div>
Script should be refered:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.min.js"></script>
Form, asks for name, gender and age, and then submitted to the submit.php treatment, under normal circumstances, and click "submit" button, the page will go submit.php process form data, and we use jquery.form plug-in, page does not jump directly completed an ajax interaction.
jQuery
We are very convenient to call jquery.form plugin using ajaxSubmit () makes the whole form ajax submission process becomes very simple.
$(function(){
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
resetForm: true,
dataType: 'json'
};
// bind to the form's submit event
$('#my_form').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
var uname = $("#uname").val();
if(uname==""){
$("#msg").html("Name can't be empty!");
return false;
}
var age = $("#age").val();
if(age==""){
$("#msg").html("Age can't be empty!");
return false;
}
$("#msg").html("Submiting...");
return true;
}
// post-submit callback
function showResponse(responseText, statusText) {
$("#msg").html('Successful submit.');
var sex = responseText.sex==1?"Man":"Female";
$("#output").html("Name: "+responseText.uname+" Sex: "+sex+" Age: "+responseText.age);
}
The code above before submitting completed forms submitted after verification and processing. After the form data submitted to submit.php, we can according to the actual situation by submit.php test data, the data is written to the database, return to the operating result, and so the operation, this is no longer listed in the code. You can see the demo example.
jquery.form plug-in also provides formToArray (), formSerialize (), fieldSerialize (), fieldValue (), clearForm (), clearFields () and resetForm () and other methods. Usually we can use forms authentication plug-ins and jquery.form used together, it will be better.