I have written code to like a publication, where clicking the like button saves the value to the database using server-side code. However, when I click the button, the page refreshes to save the value, and I’m experiencing some issues. I attempted to use JavaScript code like event.preventDefault()
, but it didn’t work. Could you suggest a better way to implement this?
echo '<form method="POST" action="profile.php" id="likeForm">';
echo '<input type="hidden" name="id_' . $publication_id . '" value="' . $publication_id . '">';
echo '<div class="button-container">';
echo '<button type="submit" id="likeButton" onsubmit="return false;">' . $heart_icon . '</button>';
echo '</div>';
echo '</form>';
I tried event.preventDefault()
,
I also tried this code:
echo '<form method="POST" action="profile.php" id="likeForm">';
echo '<input type="hidden" name="id_' . $publication_id . '" value="' . $publication_id . '">';
echo '<div class="button-container">';
echo '<button type="button" id="likeButton">' . $heart_icon . '</button>';
echo '</div>';
echo '</form>';
echo '<script>';
echo 'document.getElementById("likeButton").addEventListener("click", function() {';
echo 'var xhr = new XMLHttpRequest();';
echo 'xhr.open("POST", "profile.php");';
echo 'xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");';
echo 'xhr.onload = function() {';
echo 'if (xhr.status === 200) {';
echo 'console.log(xhr.responseText);'; // or you can show a success message here
echo '}';
echo '};';
echo 'xhr.send("id_' . $publication_id . '=' . $publication_id . '");';
echo '});';
echo '</script>';
And lastly this one:
$(function() {
$('#likeForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'profile.php',
data: $('#likeForm').serialize(),
success: function() {
alert("Data has been submitted!");
}
});
e.preventDefault();
});
});
3
Answers
Preventdefault doesn’t work for a submit, you should use return false to prevent the form to submit.
Try putting it in your success too.
You need to prevent the event so the default behavior is discarded.
Please try this.
Please find your edited code below and try it. I have try to make it simpler
TIP and NOTE:
console for any errors.
</body>
tagIn case of query or issue please leave a comment.