阻止默认表单提交行为在这个jQuery AJAX的用例中为什么失败?

huangapple go评论71阅读模式
英文:

What makes preventing the default form submission behavior fail in this use case of jQuery AJAX?

问题

  1. 我已经制作了一个使用Laravel 8的**博客应用程序**。

  2. 我目前正在尝试通过AJAX提交评论和回复评论,而不是以“传统”的方式。

  3. 评论表单:

<div id="commentSuccess-{{ $comment->id ?? '' }}" class="alert-box-ajax alert-box alert-box--success">
  您的评论正在等待审核
</div>

<div id="commentFail-{{ $comment->id ?? '' }}" class="alert-box-ajax alert-box alert-box--error">
  添加评论失败!
</div>

<form class="commentForm" method="post" action="{{ route('comment.submit') }}" autocomplete="off">
  @csrf
  <fieldset>
    <input type="hidden" name="article_id" value="{{ isset($article->id) ? $article->id : $article_id }}">
    <input type="hidden" name="parent_id" value="{{ $comment->id ?? '' }}">

    <div class="message form-field">
      <textarea name="msg" id="message" class="h-full-width" placeholder="您的留言" required></textarea>

      @error('msg')
      <p class="help-block text-danger">{{ $message }}</p>
      @enderror
    </div>
    <br>
    <input name="submit" id="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="添加评论" type="submit">
  </fieldset>
</form>
  1. 为了验证,我使用了**jQuery验证插件**(版本1.19.0)由Jörn Zaefferer制作。

  2. (jQuery)AJAX部分:

// 验证评论表单
$(".commentForm").each(function() {
    var form = $(this);
    form.validate({
        errorElement: 'p',
        errorClass: "help-block text-danger",

        submitHandler: function(event) {
            event.preventDefault();
            var $fields = form.find('textarea'),
                url = form.attr('action'),
                data = form.serialize();
            $.ajax({
                dataType: "json",
                type: "post",
                url: url,
                data: data,
                cache: false,
                success: function(response) {
                    $('#commentSuccess-' + data.article_id).slideDown(250).delay(2500).slideUp(250);
                    $fields.val('');
                },
                error: function() {
                    $('#commentFail-' + data.article_id).slideDown(250).delay(2500).slideUp(250);
                }
            });
        }
    });
});
  1. 问题:

由于某种原因,我无法找出,应该阻止“传统”表单提交的部分,event.preventDefault() 不起作用。

  1. 问题:

  2. 我做错了什么?

  3. 修复这个问题最可靠的方法是什么?

英文:

I have made a blogging application in Laravel 8.

I am currently working on submitting comments and comment replies via AJAX instead of doing it "classically".

The comment form:

&lt;div id=&quot;commentSuccess-{{ $comment-&gt;id ?? &#39;&#39; }}&quot; class=&quot;alert-box-ajax alert-box alert-box--success&quot;&gt;
  Your comment is pending
&lt;/div&gt;

&lt;div id=&quot;commentFail-{{ $comment-&gt;id ?? &#39;&#39; }}&quot; class=&quot;alert-box-ajax alert-box alert-box--error&quot;&gt;
  Failed to add comment!
&lt;/div&gt;

&lt;form class=&quot;commentForm&quot; method=&quot;post&quot; action=&quot;{{ route(&#39;comment.submit&#39;) }}&quot; autocomplete=&quot;off&quot;&gt;
@csrf
&lt;fieldset&gt;
  &lt;input type=&quot;hidden&quot; name=&quot;article_id&quot; value=&quot;{{ isset($article-&gt;id) ? $article-&gt;id : $article_id }}&quot;&gt;
  &lt;input type=&quot;hidden&quot; name=&quot;parent_id&quot; value=&quot;{{ $comment-&gt;id ?? &#39;&#39; }}&quot;&gt;

  &lt;div class=&quot;message form-field&quot;&gt;
    &lt;textarea name=&quot;msg&quot; id=&quot;message&quot; class=&quot;h-full-width&quot; placeholder=&quot;Your Message&quot; required&gt;&lt;/textarea&gt;

    @error(&#39;msg&#39;)
    &lt;p class=&quot;help-block text-danger&quot;&gt;{{ $message }}&lt;/p&gt;
    @enderror
  &lt;/div&gt;
  &lt;br&gt;
  &lt;input name=&quot;submit&quot; id=&quot;submit&quot; class=&quot;btn btn--primary btn-wide btn--large h-full-width&quot; value=&quot;Add Comment&quot; type=&quot;submit&quot;&gt;
&lt;/fieldset&gt;

</form>

For validation, I use the jQuery Validation Plugin (v1.19.0) by Jörn Zaefferer

The (jQuery) AJAX part:

// Validate comment form
$(&quot;.commentForm&quot;).each(function() {
    var form = $(this);
    form.validate({
        errorElement: &#39;p&#39;,
        errorClass: &quot;help-block text-danger&quot;,

        submitHandler: function(event) {
            event.preventDefault();
            var $fields = form.find(&#39;textarea&#39;),
                url = form.attr(&#39;action&#39;),
                data = form.serialize();
            $.ajax({
                dataType: &quot;json&quot;,
                type: &quot;post&quot;,
                url: url,
                data: data,
                cache: false,
                success: function(response) {
                    $(&#39;#commentSuccess-${data.article_id}`&#39;).slideDown(250).delay(2500).slideUp(250);
                    $fields.val(&#39;&#39;);
                },
                error: function() {
                    $(`#commentFail-${data.article_id}`).slideDown(250).delay(2500).slideUp(250);
                }
            });
        }
    });
});

The problem

For a reason I have been unable to find out, the part that should prevent "classic" form submission, event.preventDefault() does not work.

Questions:

  1. What am I doing wrong?
  2. What is the most reliable way to fix this problem?

答案1

得分: 1

在进行了一些研究后,我发现事件实际上是提交处理程序(submitHandler)中接收的第二个参数。第一个参数是表单本身。

由于某些原因,文档与实际情况不同步。

您可以尝试使用以下代码来阻止表单的默认提交行为。

submitHandler: function(form, event) {
    event.preventDefault();
}

希望这对您有所帮助。

英文:

After doing some research i have found that event is actually second parameter received in the submitHandler. The first one is form itself.

For some reasons the documentation is not in a sync.

You can try this to prevent the form default form submission.

submitHandler: function(form, event) {
      event.preventDefault();
}

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// Validate comment form
$(&quot;.commentForm&quot;).each(function(){
  var form = $(this);
  form.validate({
    errorElement: &#39;p&#39;,
    errorClass: &quot;help-block text-danger&quot;,

    submitHandler: function(_form, event) {
      event.preventDefault();
      var $fields = form.find(&#39;textarea&#39;),
      url = form.attr(&#39;action&#39;),
      data = form.serialize();
      $fields.val(&#39;&#39;);
      console.log(&quot;Submitting to &quot;+url+&quot; with data: &quot;+data);
    }
  });
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;form class=&quot;commentForm&quot; method=&quot;post&quot; action=&quot;/commentSubmit&quot; autocomplete=&quot;off&quot;&gt;
    &lt;fieldset&gt;
      &lt;input type=&quot;hidden&quot; name=&quot;article_id&quot; value=&quot;33&quot;&gt;
      &lt;input type=&quot;hidden&quot; name=&quot;parent_id&quot; value=&quot;1&quot;&gt;
      &lt;div class=&quot;message form-field&quot;&gt;
          &lt;textarea name=&quot;msg&quot; class=&quot;h-full-width&quot; placeholder=&quot;Your Message&quot; required&gt;&lt;/textarea&gt;
      &lt;/div&gt;
      &lt;br&gt;
      &lt;input name=&quot;submit&quot; class=&quot;btn btn--primary btn-wide btn--large h-full-width&quot; value=&quot;Add Comment&quot; type=&quot;submit&quot;&gt;
    &lt;/fieldset&gt;
&lt;/form&gt;
&lt;form class=&quot;commentForm&quot; method=&quot;post&quot; action=&quot;/commentSubmit1&quot; autocomplete=&quot;off&quot;&gt;
    &lt;fieldset&gt;
      &lt;div class=&quot;message form-field&quot;&gt;
          &lt;textarea name=&quot;msg&quot; class=&quot;h-full-width&quot; placeholder=&quot;Your Message&quot; required&gt;&lt;/textarea&gt;
      &lt;/div&gt;
      &lt;br&gt;
      &lt;input name=&quot;submit&quot; class=&quot;btn btn--primary btn-wide btn--large h-full-width&quot; value=&quot;Add Comment&quot; type=&quot;submit&quot;&gt;
    &lt;/fieldset&gt;
&lt;/form&gt;


&lt;script src=&quot;https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案2

得分: 0

不太熟悉jQuery验证插件,但我希望将验证代码放在文档就绪函数内会有一些改变。

$(document).ready(function() {
    $(".commentForm").each(function(){
        var form = $(this);
        form.validate({
           // ...
        });
    });
});

或者

$(function() {
    $(".commentForm").each(function(){
        var form = $(this);
        form.validate({
           // ...
        });
    });
});
英文:

Not so familiar with jQuery validation plugin but I hope putting the validation code inside a Document Ready function would make some change.

$( document ).ready(function() {
    $(&quot;.commentForm&quot;).each(function(){
        var form = $(this);
        form.validate({
           ....
    })
});

OR

$(function() {
    $(&quot;.commentForm&quot;).each(function(){
        var form = $(this);
        form.validate({
           ....
    })
});

huangapple
  • 本文由 发表于 2023年7月3日 17:29:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定