Wednesday, 8 November 2023

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

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:

<div id="commentSuccess-" class="alert-box-ajax alert-box alert-box--success">
  Your comment is pending
</div>

<div id="commentFail-" class="alert-box-ajax alert-box alert-box--error">
  Failed to add comment!
</div>

<form class="commentForm" method="post" action="" autocomplete="off">
@csrf
<fieldset>
  <input type="hidden" name="article_id" value="">
  <input type="hidden" name="parent_id" value="">

  <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"></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>

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-${data.article_id}`').slideDown(250).delay(2500).slideUp(250);
                    $fields.val('');
                },
                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?


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

No comments:

Post a Comment