skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You need to prevent the event so the default behavior is discarded.
    Please try this.

    $(function() {
            $('#likeForm').on('submit', function(e) {
                e.preventDefault();
                $.ajax({
                    type: 'post',
                    url: 'profile.php',
                    data: $('#likeForm').serialize(),
                    success: function() {
                        alert("Data has been submitted!");
                    }
                });
            });
        });
    
    Login or Signup to reply.
  3. Please find your edited code below and try it. I have try to make it simpler

      <form method="POST"  id="likeForm">
            <input type="hidden" name="id_<?php echo $publication_id;?>" value="<?php echo $publication_id;?>">
            <div class="button-container">
        <button type="submit" id="likeButton" onsubmit="return false;"><?php echo  $heart_icon;?> </button>
        </div>
      </form>
    
    
    <!--jquery -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    
    <!--custom code -->
    <script type="text/javascript">
    
            $('#likeForm').on('submit', function(e) {
                 e.preventDefault();
                $.ajax({
                    type: 'post',
                    url: 'profile.php',
                    data: $('#likeForm').serialize(),
                    success: function() {
                        alert("Data has been submitted!");
                    }
                });
               
            });
      
    </script>
    

    TIP and NOTE:

    1. When developing in case of javascript as soon as you load page please check the
      console for any errors.
    2. Because php is able to interprit the html file we can make code more readable by injecting the php in html rather than doing vice versa as i have done.
    3. When using jquery or any other library please make sure that your custom code always comes last in order.
    4. Its a good practice to place all the javascript before the end of </body> tag

    In case of query or issue please leave a comment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search