Ajax提交Form表单

<div class="iteye-blog-content-contain" style="font-size: 14px">

After clicking the submit button, FormValidation will submit the form if all the fields are valid.

If you want to do additional tasks instead of submitting the form, you can trigger the success.form.fv event:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            // Some instances you can use are
            var $form = $(e.target),        // The form instance
                fv    = $(e.target).data('formValidation'); // FormValidation 
instance

            // Do whatever you want here ...
        });
});

Inside the success.form.fv event handler, if you want to submit the form after doing your custom job, just simply use thedefaultSubmit() method:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target),
                fv    = $(e.target).data('formValidation');

            // Do whatever you want here ...

            // Then submit the form as usual
            fv.defaultSubmit();
        });
});

The next sections demonstrates one of most frequent usage — using Ajax to submit the form.

 

Using Ajax to submit form data

The following code snippet uses the jQuery's serialize() method to get the form data, and then ajax() methods to send the data to the back-end endpoint:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target),
                fv    = $form.data('formValidation');

            // Use Ajax to submit form data
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: $form.serialize(),
                success: function(result) {
                    // ... Process the result ...
                }
            });
        });
});
 

Using Ajax to submit form data including files

Assume that the form consists of file input:

<input type="file" name="uploadedFiles" multiple />

You can use FormData to collect the form data including selected files:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form    = $(e.target),
                formData = new FormData(),
                params   = $form.serializeArray(),
                files    = $form.find('[name="uploadedFiles"]')[0].files;

            $.each(files, function(i, file) {
                // Prefix the name of uploaded files with "uploadedFiles-"
                // Of course, you can change it to any string
                formData.append('uploadedFiles-' + i, file);
            });

            $.each(params, function(i, val) {
                formData.append(val.name, val.value);
            });

            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(result) {
                    // Process the result ...
                }
            });
        });
});

Please pay attention on contentType and processData options of the jQuery's ajax() method:

  • Setting contentType: false tells jQuery to not add Content-Type to the request
  • Setting processData: false tells jQuery to not convert our data (which is a FormData instance) to a string

On the server side, you can get the uploaded files under the names uploadedFiles-0

uploadedFiles-1, and so forth, depending how many files are chosen.

FormData are supported in modern browsers including IE 10+. You shouldn't use it if your application needs to support previous versions of IE such as IE 8, IE 9.
 

Using jQuery Form plugin

jQuery Form plugin allows us to submit the form, including sending files with an Ajax request easily.

The following snippet shows how to use jQuery Form's ajaxSubmit() method to send all form data, including selected files to the server:

<!-- Including jQuery Form plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/
jquery.form.min.js"></script>

<form id="testForm" method="post" class="form-horizontal">
    ...
</form>
$(document).ready(function() {
    $('#testForm')
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target);
            $form.ajaxSubmit({
                // You can change the url option to desired target
                url: $form.attr('action'),
                dataType: 'json',
                success: function(responseText, statusText, xhr, $form) {
                    // Process the response returned by the server ...
                    // console.log(responseText);
                }
            });
        });
});

 

</div>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值