首页 > 解决方案 > 如何通过ajax提交多步骤表单

问题描述

我试图在不刷新页面的情况下提交表单,我使用这个库来执行多步表单,但是最后它通过加载到表单操作来强制提交表单,我试图通过将 form.submit 设置为来停止它错误,但是当我这样做时它停止发送请求vai ajax。

我的 multstepform.js

 (function ( $ ) {
  $.fn.multiStepForm = function(args) {
  if(args === null || typeof args !== 'object' || $.isArray(args))
    throw  " : Called with Invalid argument";
  var form = this;
  var tabs = form.find('.containerformtab');
  var steps = form.find('.stepform');
  steps.each(function(i, e){
    $(e).on('click', function(ev){
    });
  });
  form.navigateTo = function (i) {/*index*/
    /*Mark the current section with the class 'current'*/
    tabs.removeClass('currentform').eq(i).addClass('currentform');
    // Show only the navigation buttons that make sense for the current section:
    form.find('.previousform').toggle(i > 0);
    atTheEnd = i >= tabs.length - 1;
    form.find('.nextform').toggle(!atTheEnd);
    // console.log('atTheEnd='+atTheEnd);
    form.find('.submitform').toggle(atTheEnd);
    fixStepIndicator(curIndex());
    return form;
  }
  function curIndex() {
    /*Return the current index by looking at which section has the class 'current'*/
    return tabs.index(tabs.filter('.currentform'));
  }
  function fixStepIndicator(n) {
    steps.each(function(i, e){
      i == n ? $(e).addClass('activeform') : $(e).removeClass('activeform');
    });
  }
  /* Previous button is easy, just go back */
  form.find('.previousform').click(function() {
    form.navigateTo(curIndex() - 1);
  });

  /* Next button goes forward iff current block validates */
  form.find('.nextform').click(function() {
    if('validations' in args && typeof args.validations === 'object' && !$.isArray(args.validations)){
      if(!('noValidate' in args) || (typeof args.noValidate === 'boolean' && !args.noValidate)){
        form.validate(args.validations);
        if(form.valid() == true){
          form.navigateTo(curIndex() + 1);
          return true;
        }
        return false;
      }
    }
    form.navigateTo(curIndex() + 1);
  });

  form.find('.submitform').on('click', function(e){
    e.preventDefault();
    if(typeof args.beforeSubmit !== 'undefined' && typeof args.beforeSubmit !== 'function')
      args.beforeSubmit(form, this);
    //check if args.submit is set false if not then form.submit is not gonna run, if not set then will run by default        
    if(typeof args.submit === 'undefined' || (typeof args.submit === true /*'boolean'*/ && args.submit)){
      form.submit();
    }
    return form;
  });

  /*By default navigate to the tab 0, if it is being set using defaultStep property*/
  typeof args.defaultStep === 'number' ? form.navigateTo(args.defaultStep) : null;

  form.noValidate = function() {

  }
  return form;
 };
 }( jQuery ));

我的 index.html

    <form action="<?= URL; ?>/Page/add" method="POST" id="myForm">
        <div class="containerformtab">
                <label for="name">Name</label>
                <input type="text" name="name" id="name">
        </div>
        <div class="containerformtab">
                <label for="password">Password</label>
                <input type="password" name="password" id="password">
        </div>
        <div style=" padding:10px;">
           <div style="float:left">
             <button type="button" class="submitform create-btn" id="insertchurch">CREATE</button>
              <button type="button" class="previousform previous_btn">Previous</button>
              <button type="button" class="nextform next_btn">Next</button>
           </div>
       </div>
    </form>

我的 custom.js

             $(function(){

     // validate password match
     $.validator.addMethod("valueNotEquals", (value, element, arg)=>{
      return arg !== value;
     }, "Value must not equal arg.");


     var val = {
        rules: {
            name: {
                required: true,
                minlength: 2
            },
            password: {
                required: true,
                minlength: 5
            },
        },
        messages: {
        }
    }

   $("#myForm").multiStepForm({
            // submitHandler: function(form){},

            beforeSubmit: function(form,submit){
                insert();
                return false;
            }
    }).navigateTo(0); 
     })(jQuery);

    // ajax call
    // function to add church
    function insert()
    {
        var name = $('#name').val();
        var url     = $('#myform').attr('action');

        $.ajax({
            url : url,
            method : 'POST',
            data : { name: name },
            success : (response) =>{
                $('.message').html(response).show();
                $('#createChurch').trigger('reset');
            },
            error : (response) =>{

            }

   });

标签: javascriptphpjqueryhtmlajax

解决方案


使用.submit(或.on)监听submitJavaScript 事件。

然后.preventDefault()在事件上取消默认行为(提交表单)

$("#myForm").submit(function(e){
    e.preventDefault();
    return false;
});

推荐阅读