I have a simple commenting system that I'm using AJAX to comment and fetch comments. But I have started experiencing duplicated comments for each comment. Here is how it's going on: the first comment is not duplicated, the second comment gets doubled(gets duplicated), the third gets tripled...and so on in that trend. How do I fix that?
`//THIS IS THE COMMENTING PHP FILE
<?php
include '../DB-config/db-config.php';
if (!empty($_POST['comment_text']) && !empty($_POST['user_email']) && !empty($_POST['user_id']) && !empty($_POST['page_url'])) {
$comment = $connection->real_escape_string($_POST['comment_text']);
$user_email = $connection->real_escape_string($_POST['user_email']);
$user_id = $connection->real_escape_string($_POST['user_id']);
$page_url = $connection->real_escape_string($_POST['page_url']);
$INSERT = "INSERT INTO comments (user_id, user_email, page_url, parent_id, comment) VALUES ('" . $user_id . "', '" . $user_email . "','" . $page_url . "', '0', '" . $comment . "')";
$sql = mysqli_query($connection, $INSERT);
}
?>`
//AJAX
`$('#comment-post').on('click', function (e) {
$(document).on('submit', '#comment-writting form', function (event) {
event.preventDefault();
if ($('#comment-textarea').val() == '') {
$('#comment-notice').html('Write a comment...').css('color', 'red');
$('#comment-notice').show();
}
else {
$('#comment-notice').hide();
var user_email = $('#user_email').val();
var user_id = $('#user_id').val();
var page_url = window.location.search;
var comment_text = $('#comment-textarea').val();
$.ajax({
url: "../Ajax/comment.php",
method: 'POST',
data: { user_email: user_email, user_id: user_id, page_url: page_url, comment_text: comment_text },
success: function (response) {
$('#comment-textarea').empty();
$('.emojionearea.emojionearea-inline > .emojionearea-editor').empty();
}
});
}
})
});`
For anyone who may be having the same problem, I have fixed my problem by using element.unbind(eventType) after the event has performed its task
for example in my case: $('#comment-post').unbind('click'); after Ajax response.