I am generating dynamic content for my modal-body
which includes a comment submit form. I put together a function that on click of the submit button is supposed to trigger an AJAX call to handle the comment submission, but for whatever reason nothing is happening once I click the button.
I tried various ways of trapping the trigger event like $('#form').on('submit', function(e) {
or $('.class').click(function(){
but none trigger anything.
The only time I get a result is when I change the submit button type from type="button"
to type="submit"
, however, this results in an unwanted full page reload which is not desired as the modal is supposed to remain open.
Appreciate any advice, obviously the console is empty and any alert();
are not triggered as well.
Modal Body Content - Comment Form - populated via previous AJAX call
<!-- Begin post comment form -->
<form id=\"modal-comment-form\" name=\"modal-comment-form\" class=\"form margin-top-50\" action=\"\" method=\"\">
<h4>leave a comment:</h4>
<div class=\"row\">
<div class=\"col-lg-12\">
<div class=\"form-group\">
<textarea class=\"form-control\" id=\"modal-comment-message\" name=\"modal-comment-message\" rows=\"3\" placeholder=\"your comment*\" required></textarea>
<input id=\"modal-comment-task-id\" name=\"modal-comment-task-id\" type=\"hidden\" class=\"form-control\" placeholder=\"\" value=\"".$task_id."\" readonly required>
</div>
</div>
</div>
<div class=\"row\">
<div class=\"col-lg-12\">
<button type=\"button\" id=\"modal_comment_submit\" name=\"modal_comment_submit\" class=\"btn btn-primary modal-comment\">submit comment</button>
</div>
</div>
</form>
<!-- End post comment form -->
jQuery to check modal comment button submit
$(document).ready(function() {
// modal comment submit
$('#modal_comment_submit').click(function(e) {
console.log('Comment submit button clicked.');
// check if textarea has content or not
if ($('#modal-comment-message').val() != '') {
console.log('Modal comment textarea is not empty');
$('#modal_comment_submit').prop('disabled', true); // disable submit button
var task_id = e.find('input[name="modal-comment-task-id"]').val(); // obtain task id from hidden field
$.ajax({
type: 'POST',
url: 'path/to/script.php',
data: 'action=add_new_comment&app_id=4&article_id=' + task_id + '&user_id=1&' + $('#modal-comment-form').serialize(),
cache: false,
success: function(response) {
console.log(response);
// show success message
$('#comment_output').html(response);
// remove success message after 5 sec
setTimeout(function() {
$('#comment_output').empty().hide();
}, 5000);
// enable submit button
$('#modal_comment_submit').prop('disabled', false);
},
error: function(xhr, status, error) {
console.log('Ajax POST request failed.');
console.error(xhr);
alert('Error: ' + xhr);
}
});
} else {
console.log('Form on submit is invalid');
alert("Please enter a comment");
}
});
});