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:
- What am I doing wrong?
- What is the most reliable way to fix this problem?
2
Answers
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.
Not so familiar with jQuery validation plugin but I hope putting the validation code inside a Document Ready function would make some change.
OR