0

I have a like/unlike button and number of like field and it echos a variable that gets number of likes as follows:

PHP-HTML:

<a onclick="javascript:likes(<?php echo $row['Question_ID'];?>);"><button type="submit"  class="btn btn-custom btn-sm liketoggle" name ="like"><span>likes: <?php echo $row['likes'];?></span>
<button type="submit"  class="btn btn-custom btn-sm liketoggle" name ="like"></button></a>

//Printing 'Like' if its been liked by user, and 'Unlike' if not liked by user
<? $qid = $row['Question_ID']; $query2 = "SELECT * FROM likes WHERE 
       user_id='$user_id' and qid = '$qid'";
      $results2 = mysqli_query($con,$query2);
      if(mysqli_num_rows($results2) == 0){ echo '<span>Like</span>';} 
      else{echo '<span>Unlike</span>';}?></button>

AJAX:

function likes(qid) {

    if (ajax.readyState == 4 || ajax.readyState == 0) {
        ajax.open("POST", 'likes.php?qid='+qid, true);

        ajax.onreadystatechange = queried(type);
        ajax.send();
    }
}

Javascript - To toggle like/unlike:

$(".liketoggle").click(function () {
            $(this).find("span").text(function(i, v){
               return v === 'Like' ? 'Unlike' : 'Like'
               return v === 'Unlike' ? 'Like' : 'Unlike'
            })
        });

Is there I way I can increment the number of likes ($row['likes']) when user hits on like, and the same way decrements when unliking? How is this possible? The AJAX is doing the job in the database but I want to change the number of likes in the front end.

Jawad Sleiman
  • 55
  • 1
  • 9
  • You will need a PHP function that querys the db for the number of likes and send it back in an AJAX request –  Mar 12 '19 at 17:19
  • I don't want to refresh the page. does it go in the likes.php? and how I can send it back with AJAX? @Chipster – Jawad Sleiman Mar 12 '19 at 17:21
  • https://stackoverflow.com/a/20150474/2191572 – MonkeyZeus Mar 12 '19 at 17:21
  • @MonkeyZeus In your example you are alerting whats came back from PHP file. How I can print this in an html tag inside my page? which is my php variable in the page. – Jawad Sleiman Mar 12 '19 at 17:29
  • @JawadSleiman That's basic DOM manipulation with jQuery. There are plenty of resources for learning how to do that. Your `$(this).find("span").text(` code is very similar to what you need. – MonkeyZeus Mar 12 '19 at 18:52

1 Answers1

0

Try specifying an id in your span:

<span id="likes">likes: <?php echo $row['likes'];?></span>

Then in your ajax place the response from your Ajax call into that html tag by using $('#likes').html(response):

Example of Ajax:

function likes(qid) {

    $.ajax({
        data: {qid: qid},
        type: 'POST',
        url: 'likes.php',
        success: function (response) {
            // Insert response into html
            $('#likes').html(response);
    }

}
Kevin
  • 22
  • 4