Jquery.form.js (Ajax form submission)

Source: Internet
Author: User

Form Plugin Address:

Official website: http://malsup.com/jQuery/form/

Translation Address: http://www.aqee.net/docs/jquery.form.plugin/jquery.form.plugin.html#getting-started

I. Preparatory work

Write a form:

<form id= "Reg" action= "123.php" method= "POST" >

<p>
<label for= "User" > Account:</label>
<input type= "text" name= "user" class= "text" id= "user" title= "/>
</p>
<p>
<label for= "pass" > Password:</label>
<input type= "password" name= "pass" class= "text" id= "pass"/>
</p>

<input type= "Submit" value= "Submit Comment"/>

</form>

Introduce jquery and form Plugin JavaScript script files:

<script type= "Text/javascript" src= "path/to/jquery.js" ></script><script type= "Text/javascript" src= "Path/to/form.js" ></script>
Two. Core approach

The Form.js plugin has two core methods: Ajaxform () and Ajaxsubmit (), which gather functionality from controlling form elements to deciding how to manage commits.

ajaxForm

Preprocess the forms that will be submitted using AJAX, adding all the event listeners that need to be used. It is not submitted to this form. Use the functions in the page ready ajaxForm to prepare the Ajax submissions for the forms on your page. ajaxFormrequires 0 or one parameter. The only parameter can be a callback function or an optional parameter object.

// Ajaxform Submission Method   $ (' #reg '). Ajaxform (function  () {  alert (' Submit succeeded! ');  

Note: Using the Ajaxform () method, Ajax commits are implemented directly. The default behavior is automatically blocked, and the default page that it submits is the value of the Action property of the form control. The way to commit is the value of the method property.

Ajaxsubmit

Immediately submit the form via Ajax. The most common use is to invoke a user's action to submit a form when it responds. ajaxFormrequires 0 or one parameter. The only argument can be a callback function or an optional parameter object.

// Ajaxsubmit () Submission method   $ (' #reg '). Submit (function  () {  $ (this). Ajaxsubmit(function  () {  Alert (' Submit success! ');  });   return false ;  Ajaxsubmit does not automatically block default commits, it needs to be blocked by itself. This prevents default direct commit behavior});  

Note: the Ajaxform () method, which is submitted directly against the form, prevents the default behavior. The Ajaxsubmit () method, because it is for the submit () method, requires manual blocking of the default behavior. and using the Validate.js verification plugin, then Ajaxsubmit () is more suitable for us.

Question: The difference between ajaxform () and Ajaxsubmit ():

Answer: $ ("#form1"). Ajaxform (); The equivalent of two lines:

$ ("#form1". Submit) (function () {

$ ("#form1"). Ajaxsubmit ();

return false;

})//That is, Ajaxfrom () automatically blocks form submission. and Ajaxsubmit () does not automatically prevent form submission, want to prevent form submission, to return false;

Three. Optional parameter Item Object

ajaxFormand ajaxSubmit both support a large number of optional parameters, which are passed in through an optional parameter item object. The optional parameter item object is just a simple JavaScript object that contains some attributes and some values:

Target
replaces the contents of the specified page element with the contents returned by the server side. This value can be represented by a jquery selector, or a jquery object, a DOM element.
Default value: null
Url
the address of the form submission.
Default value: action The value of the form
Type
The way the form is submitted, ' GET ' or ' POST '.
Default value: The method value of the form ("GET" if not indicated)
Beforesubmit
the method to execute before the form is submitted. This can be used before the form is submitted for preprocessing, or form validation. If the function specified by ' Beforesubmit ' returns false, the form is not committed. The ' beforesubmit ' function call requires 3 parameters: form data in the form of an array, form objects in the form of JQuery objects, and optional objects to be passed to the ajaxform/ajaxsubmit. form data in the form of an array is in the following format:
[ { name: ‘username‘, value: ‘jresig‘ }, { name: ‘password‘, value: ‘secret‘ } ]
Default value: null
Success
the function to execute when the form is committed. If the ' success ' callback function is specified, the method is executed when the server side returns a response to the form submission. The values of ResponseText and Responsexml are passed into this parameter (this depends on the type of datatype).

Default value:null

DataType
Specifies the type of data returned by the server response. One of them: null, ' xml ', ' script ', or ' json '. This dataType option is used to indicate how you want to handle the data returned by the server side. This jQuery.httpData corresponds directly to the method. Here are the options you can use:

' xml ': if DataType = = ' xml ' The data returned by the server is treated as XML, in which case the ' success ' specified callback function is passed in Responsexml data

' JSON ': if DataType = = ' json ' then the data returned by the server will be executed and passed into the ' success ' callback function

' script ': if dataType = = ' script ' then the data returned by the server will be executed in context

Default value:null

Semantic
A Boolean value that indicates whether the order of data submitted by the table dropdowns needs to be strictly in the order of semantics. The data for a general form is serialized in chapeau order, unless there is an element in the form type="image" . This is required only if the form must have strict order and there is a form type="image" .
Default value: false
Resetform
A Boolean value that indicates whether a reset is required after the form is submitted successfully.
Default value: null
ClearForm
A Boolean value that indicates whether the form needs to be emptied after it has been submitted successfully.
Default value: null
Iframe
Boolean value that indicates whether the form needs to be submitted to an IFRAME. This is used when there is a file field in the form to upload files. For more information, refer to the file uploads document in the Code sample page.
Default value: false
Reference Code:
$ ("#reg"). Submit (function() {        $( This). Ajaxsubmit ({URL:"123.php",//set the URL of the submission to override the Action propertyTarget: "#box",//the contents returned by the server are stored in #box.Type: "GET", Datetype:NULL,//Xml,json,script, default is null            //Clearform:true,//After successful submission, clear the form            //Resetform:true,//After successful submission, reset formData: {//add additional data submissionsAAA: ' BBB ', CCC:' DDD '}, Beforesubmit:function(FormData, Jqform, Options) {//execute before data is submitted, typically for data validation                //returns False if the data validation is not valid, and does not allow the commit. True by default                //alert (formdata[0].name);//Get the name of the pass form element                //alert (formdata[0].value);//Get the value of the pass form element                //alert (jqform[0].user.value);//jquery object to get form                //alert (Options.url); Get the current Options settings Properties                return true; }, Success:function(Responsetext,statustext) {//Callback when successfulAlert (ResponseText +statustext); //alert (' Thanks for your comment! '); }, Error:function(event, ErrorText, ErrorType) {//Error callback alert (ErrorText+ErrorType);        },        }); return false; });
Four Tool methods

In addition to providing two core methods, Form.js provides a number of common tool methods. These methods are primarily used to process data or forms before or after submission.

// form Serialization alert ($ (' #reg '). Formserialize ()); // serializes a field alert ($ (' #reg #user '). Fieldserialize ()); // get the value of a field alert ($ (' #reg #user '). Fieldvalue ()); // Reset the form $ (' #reg '). Resetform ()// empty a field $ (' #reg #user '). Clearfields ();

Jquery.form.js (Ajax form submission)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.