The issue here lies in the usage of event.preventDefault()
. It should be placed at the beginning of the event handler and not within the submitHandler
. The submitHandler
is a method provided by the jQuery Validate plugin, not by jQuery's event system. In this case, you do not actually have direct access to the event object for the submit event, so calling event.preventDefault()
will not work.
Here's how you can modify your code to correctly use event.preventDefault()
:
$(".commentForm").on('submit', function(event) {
event.preventDefault();
var form = $(this);
if (!form.valid()) return; // You should add validation here
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);
}
});
});
This code attaches a 'submit' event handler to each form, then uses event.preventDefault()
to prevent the form from being submitted the default way. If the form is valid, an AJAX request is made. Otherwise, the function returns and no AJAX request is made.
One more thing, you are using template strings (${...}
) in your selectors inside the success
and error
callbacks. However, data.article_id
does not seem to exist because data
is a serialized string. You would need to pull the article_id
from the form before serializing. Consider modifying the code to something like this:
$(".commentForm").on('submit', function(event) {
event.preventDefault();
var form = $(this);
if (!form.valid()) return; // You should add validation here
var articleId = form.find('input[name="article_id"]').val(),
$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-${articleId}`).slideDown(250).delay(2500).slideUp(250);
$fields.val('');
},
error: function() {
$(`#commentFail-${articleId}`).slideDown(250).delay(2500).slideUp(250);
}
});
});
Here we're grabbing the article_id
from the hidden input field before we serialize the form. This allows us to use it in our AJAX callbacks.s