Bobojquery form plug-in ajaxform usage explanation

Source: Internet
Author: User

Main methods of plug-in:

Ajaxform
Ajaxsubmit
Formtoarray
Formserialize

Fieldserialize
Fieldvalue
ClearForm
Clearfields
Resetform

Example code:

1 // wait for the DOM to be loaded
2 $(document).ready(function() { 
3    // bind ‘myForm‘ and provide a simple callback function  
4    $(‘#myForm‘).ajaxForm(function() {  
5        alert("Thank you for your comment!"); 
6     });
7 });

: Http://malsup.github.com/jquery.form.js

Form plug-in API

English Original: http://www.malsup.com/jquery/form/#api

The form plug-in API provides several ways for you to easily manage form data and make form submissions.

Ajaxform ()

Add all the required event listeners to prepare for the AJAX submission form. Ajaxform cannot submit the form. In the ready function of document, use Ajaxform to prepare the form for the AJAX submission. A ajaxform accepts 0 or 1 parameters. This single parameter can be either a callback function or an options object.
Available links (chainable): Yes.

Instance:

$ (' #myFormId '). Ajaxform ();

Ajaxsubmit ()

The form is immediately submitted by Ajax. In most cases, ajaxsubmit is called to respond to a user submitting a form. A ajaxsubmit accepts 0 or 1 parameters. This single parameter can be either a callback function or an options object.
Available links (chainable): Yes.

Instance:

1 // 绑定表单提交事件处理器
2 $(‘#myFormId‘).submit(function() {
3     // 提交表单
4     $(this).ajaxSubmit();
5     // 为了防止普通浏览器进行表单提交和产生页面导航(防止页面刷新?)返回false
6     returnfalse;
7    });
8
9 formSerialize()

Serialize (or serializes) the form into a query string. This method returns a string in the following format: Name1=value1&name2=value2.
can link (chainable): No, this method returns a string.

Instance:

var queryString = $ (' #myFormId '). Formserialize ();

Data can now be submitted using $.get, $.post, $.ajax, etc.
$.post (' myscript.php ', queryString);

Fieldserialize ()

Serializes (or serialize) a form's field elements into a single query string. This is handy when only a subset of the form fields need to be serialized (or serializable). This method returns a string in the following format: Name1=value1&name2=value2.
can link (chainable): No, this method returns a string.

Instance:

var queryString = $ (' #myFormId. Specialfields '). Fieldserialize ();


Fieldvalue ()

Returns the value of the form element that matches the inserted array. Starting with version 0.91, the method will always return data as an array. If the element value is judged to be invalid, the array is empty, otherwise it will contain one or more element values.
can link (chainable): No, the method returns an array.

Instance:

Get Password Input value
var value = $ (' #myFormId:p assword '). Fieldvalue ();
Alert (' The password is: ' + value[0]);


Resetform ()

Restores the form to its original state by invoking the original Dom method of the form element.
Available links (chainable): Yes.

Instance:

$ (' #myFormId '). Resetform ();


ClearForm ()

Clears the form element. This method empties all text (text) input fields, password (password) input fields, and text area (textarea) fields, clearing the selection in any SELECT element. and resets all the Radio (radio) buttons and the multi-select (checkbox) buttons to unselected states.
Available links (chainable): Yes.

$ (' #myFormId '). ClearForm ();


Clearfields ()

Clears the field element. Easy to use only if some form elements need to be cleared.
Available links (chainable): Yes.

$ (' #myFormId. Specialfields '). Clearfields ();

Options Object

Both Ajaxform and Ajaxsubmit support a wide range of option parameters, which can be provided using an options object. The options is just a JavaScript object that contains a collection of properties and values as follows:

Target

Indicates the element in the page that is updated by the server response. The value of the element may be specified as a jquery selector string, a jquery object, or a DOM element.
Default value: null.

Url

Specifies the URL to submit the form data.
Default value: The Action property value of the form

Type

Specifies the method by which the form data is submitted: "GET" or "POST".
Default value: The Method property value of the form (if no default is found for "GET").

Beforesubmit

The callback function that was called before the form was submitted. The "Beforesubmit" callback function is provided as a hook to run the pre-commit logic or to validate the form data. If the "Beforesubmit" callback function returns false, the form will not be committed. The "Beforesubmit" callback function has three invocation parameters: form data in array form, jquery form objects, and options objects in the incoming ajaxform/ajaxsubmit. The table singular group accepts data in the following ways:

[{name: ' username ', value: ' Jresig '}, {name: ' Password ', value: ' Secret '}]

Default value: null

Success

callback function that is called after the form has been successfully committed. If the "Success" callback function is provided, it is called when the response is returned from the server. The datatype option value is then determined to return the value of ResponseText or Responsexml.
Default value: null

DataType

The type of data expected to be returned. NULL, "XML", "script", or "JSON" one of them. DataType provides a method that specifies how the server's response is handled. This is directly reflected in the Jquery.httpdata method. The following values are supported:

' XML ': if datatype = = ' xml ', the server response will be treated as XML. Also, if the "success" callback method is specified, the Responsexml value is returned.

' JSON ': if datatype = = ' json ', the server response will be evaluated and passed to the ' success ' callback method if it is specified.

' Script ': if datatype = = ' script ', the server response will be evaluated as plain text.

Default value: null (server returns RESPONSETEXT value)

Semantic

Boolean flag indicating whether data must is submitted in strict semantic order (slower). Note that the normal form serialization was done in semantic order with the exception of input elements of type= "image". You should only set the semantic option to true if your server have strict semantic requirements and your form contains an INPUT element of type= "image".
Boolean flag that indicates whether the data must be strictly in semantic order (slower? ) to commit. Note: In general, forms have been serialized (or serialized) in semantic order, in addition to the INPUT element type= "image". If your server has strict semantic requirements, and the form contains an INPUT element with a type= "image", you should set semantic to true. This paragraph, because it is incomprehensible, may not be translated into words, but please correct. )
Default value: False

Resetform

A Boolean flag that indicates whether the form submission succeeds if it is reset.
Default Value:null

ClearForm

A Boolean flag that indicates whether the form data is purged if the form is submitted successfully.
Default value: null

Instance:

Prepare the Options object.

1 varoptions = {
2     target:     ‘#divToUpdate‘,
3     url:        ‘comment.php‘,
4     success: function() {
5       alert(‘Thanks for your comment!‘);
6     } };
7
8    // 将options传给ajaxForm
9 $(‘#myForm‘).ajaxForm(options);


Note: The options object can also be used to pass values to the $.ajax method of jquery. If you are familiar with the options supported by $.ajax, you can use them to pass the options object to Ajaxform and Ajaxsubmit.

Ajaxform () is suitable for handling Ajax technology as a form submission (the action, ID, method, preferably providing a submit button in a form) that provides the form, and it greatly simplifies the problem of data transfer when using AJAX technology to submit a form. Using Ajaxform () You do not need to get the value of each form property individually, in JavaScript, and you do not need to pass the data through URL rewriting after the request path. Ajaxform () automatically collects the value of each property in the current form and submits it to the destination URL as a form submission. Submitting data in this way is more secure and easier to use, without having to write too much redundant JavaScript code

$ (document). Ready (function () {

Registerform ' form ID

Data callback

$ (' #registerForm '). Ajaxform (function (data) {

alert (data);//callback result after the AJAX request is popped

});

});

Ajaxsubmit () applies to the mechanism of an event to submit form forms in Ajax (hyperlinks, Picture click events), which act like Ajaxform (), but are more flexible because he relies on the event mechanism to use the method whenever an event exists. You simply specify the Action property of the form, and you don't need to provide a submit button.

$ (document). Ready (function () {

$ (' #btn '). Click (function () {

$ (' #registerForm '). Ajaxsubmit (function (data) {

alert (data);

});

return false;

});

});

The function of this code is to use the Ajaxsubmit () method to submit the form to the form's action-referring path when the button click event of the form ID btn is triggered by the AJAX technique

formserialize () is to serialize all the table cells in a form as key,value as values, which requires you to set the table cell Name property and the value of the table cell value for each form element, It is also best to set the ID conveniently to locate form elements in jquery. To use this method, you must set the table cell Name property and populate the value of table cell value, I forgot to set the Name property when I first used it, and finally found this error with the help of a colleague for a long time.

var str=$ (' #registerForm '). Formserialize (); Registerform as Form ID

alert (str);

Fieldserialize() is the serialization of form elements in a form with name as key,value as a value. This requires you to set the table cell Name property and the value of the Table element value to fill for each of the form elements.

var str=$ (' #username). Fieldserialize ();

alert (str);

DEMO:

$ ("#crop_form"). Ajaxform ({
Success:function (data) {
if (data! = undefined && data! = NULL) {
If (data.msg = = 0) {
Alert ("Please upload the picture! ");
} else if (data.msg = =-1) {
Alert ("file format is incorrect"),
} else if (data.msg = =-2) {
alert ("Upload picture cannot exceed 10m! ");
} else if (data.msg = =-3) {
Alert ("There is an exception, please try again later!! ");
} else {
var data = json.parse (data),//converted to JSON format
var path = "/upload/" + data.msg;
$ ("#Name"). Val (data.msg );
Userheadutil.initialize (path);
}
}
}
});

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.