简体   繁体   中英

jQuery Validation plugin and ajax form submit

I have a simple multipart/form-data form submitted with ajax after validation using jQuery Validation Plugin.

I disable the submit button before submit and after successful form submission enable the submit button and reset all the form fields. The form code is working on Chromium Browser on a Debian Box.

Is there a better/cleaner way of doing this?

<form class="aForm" enctype="multipart/form-data">
File To Upload: <input class="aData" type="file" name="aData" /><br/>
Name of User: <input type="text" name="aName" class="aName" placeholder="Name" 
/><br/>
Date: <input type="text" name="aDate" class="aDate" placeholder="Date" /></br/>
<input type="hidden" value="5f25c045bf33ac72fcf5f8bc23b4c862d220d385" name="csrfToken" >

<button class="aButton">Button</button>
</form>

$(document).ready(function(){
  $(".aForm").validate({
    rules: {
      aData: {
        required: true,
        extension: "png|jpg",
      },
      aName: "required",
      aDate: "required"
    },
    messages: {
      aData: "No Data",
      aName: "No Name",
      aDate: "No Date"
    },
    submitHandler: function(){
      $('.aButton').prop('disabled', true);
      var formData = new FormData($('.aForm')[0]);
      console.log(formData);
      $.ajax({
        url: 'ajax.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success:
          function(data){
            alert(data);
            $('.aForm')[0].reset();
            $('.aButton').prop('disabled', false);
          },
        error: 
        function(jqXHR, textStatus){
          console.log(textStatus);
        }

      });
}
});
});

Above block of codes are working in live production without any problem. Tested on IE9 to IE 11, Chrome on windows and Linux. There are no Firefox users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM