Search code examples
phpjqueryfavorites

Adding post to favorite with PDO and SQL


I have implemented Add to favorite using PHP and SQL, So that user can save there favorite post in database and Remove form favorite

I used below code :

    function checkFavorite($mbid, $pid, $conn) {
        $stmt = $conn->prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id");
        $stmt->execute(array(':mid' => $mbid, ':id' => $pid));
        $count = $stmt->rowCount();
        if ($count == 0) {
            echo "<div class='button' data-method='Like' data-user-id=" . $mbid . " data-director-id=" . $pid . "><i class='mi' id=" . $pid . ">favorite_border</i>Add Favorite</div>";
        } else {
            echo "<div class='button' data-method='Unlike' data-user-id=" . $mbid . " data-director-id=" . $pid . "><i class='mi mi_sml text-danger' id=" . $pid . ">favorite</i>Remove Favorite</div>";
        }
    }

    $email = 'user@user.com';
    // Query to get the user_id
    $stmt = $conn->prepare('SELECT memberID FROM members WHERE email = :email AND active="Yes" ');
    $stmt->execute(array(':email' => $email));
    $row = $stmt->fetch();
    $mbid = $row['memberID'];

    $pid = '4';
    // Query to Get the Director ID
    $stmt = $conn->prepare('SELECT * FROM allpostdata WHERE id =:id');
    $stmt->execute(array(':id' => $pid));
    $result = $stmt->fetchAll();
    foreach ($result as $row) {

        echo "<p>Director: " . $row['tit'] . "</p> ";
        $fav_image = checkFavorite($mbid, $pid, $conn);
        echo "Favorite? : " . $fav_image . "";
    }

Script

        jQuery(document).ready(function ($) {
            $('.button').on('click', function (e) {
                e.preventDefault();
                const user_id = $(this).attr('data-user-id');
                const director_id = $(this).attr('data-director-id');
                const method = $(this).attr('data-method');
                if (method === "Like") {
                    $(this).attr('method', 'Unlike'); // Change the div method attribute to Unlike
                    $('#' + director_id).replaceWith('<i class="mi mi_sml text-danger" id="' + director_id + '">favorite</i>Remove Favorite'); // Replace the image with the liked button
                } else {
                    $(this).attr('method', 'Like');
                    $('#' + director_id).replaceWith('<i class="mi mi_sml" id="' + director_id + '">favorite_border</i>Add Favorite');
                }
                $.ajax({
                    url: 'favs.php', // Call favs.php to update the database
                    type: 'GET',
                    data: {user_id: user_id, director_id: director_id, method: method},
                    cache: false,
                    success: function (data) {
                    }
                });
            });
        });

enter image description here

When you look at image you can see

  1. replaceWith doesn't change button and text
  2. And in XHR request all request method are send as method="like"

but when request is send the data are saved and no error in console.

So how do i change text for Add to favorite to Remove from favorite when clicked in button.


Solution

  • I think this is what you need! Here is what I used in a demo a few years ago, you can edit to your requirements.

    Add your update url to texts like me and remove.

    $(document).ready(function () {
    
        $(".like button").click(function () {
            if ($(this).hasClass('btn')) {
                $(this).html('remove').toggleClass('btn mybtn');
            } else {
                $(this).html('Like me').toggleClass('mybtn btn');
            }
        });
    });
    .mybtn {
        color: red;
    }
    .btn {
        color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="like">
        <p>Like</p>
        <button class="btn">Like me</button>
    </div>

    Demo

    UPDATE : Sorry I was away from pc! it should be very simple to inject in your codes:

    I guess your php codes are In Your favs.php I did try like this for response in favs.php echo 'response';

    Html button! you can change to your class :

    $(document).ready(function () {
    	$(".button").click(function (e) {
    	e.preventDefault();
    	const user_id = $(this).attr('data-user-id');
    	const director_id = $(this).attr('data-director-id');
    	const method = $(this).attr('data-method');	
            if (method === "Like") {
                $(this).html('<i class="mi mi_sml text-danger" id="' + director_id + '">favorite</i>Remove Favorite').toggleClass('button mybtn');
                //Change remove text to your i class
            } else {
                $(this).html('<i class="mi mi_sml" id="' + director_id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
                //Change Like me text to your i class 
                //you can remove or edit class mybtn in both remove and like
            }
    	$.ajax({
    		url: 'favs.php',
    		type: 'GET', // type not method
    		data: {user_id: user_id, director_id: director_id, method: method},
    		cache: false,
    		success: function(data) {
    			alert(data);
    		}
    	});
    });
    });
    .mybtn {
        color: red;
    }
    .btn {
        color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="like">
        <p>Like</p>
        <button type="submit" class="btn">Like me</button>
    </div>

    I might have some mistakes like class name etc... you can edit and make it suitable for your requirements.

    I tested its working fine. SOLVED