skip to Main Content

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:

<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="Your Message" 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="Add Comment" type="submit">
    </fieldset>
</form>

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

The (jQuery) AJAX part:

// Validate comment form
$(".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').slideDown(250).delay(2500).slideUp(250);
          $fields.val('');
        },
        error: function() {
          $('#commentFail').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?

2

Answers


  1. 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();
    }
    
    // Validate comment form
    $(".commentForm").each(function(){
      var form = $(this);
      form.validate({
        errorElement: 'p',
        errorClass: "help-block text-danger",
    
        submitHandler: function(_form, event) {
          event.preventDefault();
          var $fields = form.find('textarea'),
          url = form.attr('action'),
          data = form.serialize();
          console.log("Submitting to "+url+" with data: "+data);
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="commentForm" method="post" action="/commentSubmit" autocomplete="off">
        <fieldset>
          <input type="hidden" name="article_id" value="33">
          <input type="hidden" name="parent_id" value="1">
          <div class="message form-field">
              <textarea name="msg" class="h-full-width" placeholder="Your Message" required></textarea>
          </div>
          <br>
          <input name="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="Add Comment" type="submit">
        </fieldset>
    </form>
    <form class="commentForm" method="post" action="/commentSubmit1" autocomplete="off">
        <fieldset>
          <div class="message form-field">
              <textarea name="msg" class="h-full-width" placeholder="Your Message" required></textarea>
          </div>
          <br>
          <input name="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="Add Comment" type="submit">
        </fieldset>
    </form>
    
    
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
    Login or Signup to reply.
  2. 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() {
        $(".commentForm").each(function(){
            var form = $(this);
            form.validate({
               ....
        })
    });
    

    OR

    $(function() {
        $(".commentForm").each(function(){
            var form = $(this);
            form.validate({
               ....
        })
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search