-2

i want add user like to post on page load i.e i want to make the like botton show liked if user already liked the post but it not working this is my ajax code

for (var l = 0; l < 5; l++) {
          this_comment_id = $('#like_check_'+l).attr('data-id');
              $.ajax({  
                    url:"comment_post.php",  
                    type: 'POST', 
                    data:{comment_check:this_comment_id},  
                    dataType: 'text',  
                    success:function(data)
                    {  
                          if (data.search("ok") > -1) {
                                $('#like_check_'+l).addClass("red_heart");
                          }else if(data.search("unliked") > -1){
                                $('#like_check_'+l).removeClass("red_heart");
                          }
                    }
              })
    }

it is meant to add the red_hearth to liked post by the user in this html element

<i onclick="like_post(this)" class="fas fa-heart float-right p-1 my-1 mr-3" data-id="1" id="like_check_0" data-toggle="tooltip" data-placement="top" title="I like it"></i>
<i onclick="like_post(this)" class="fas fa-heart float-right p-1 my-1 mr-3" data-id="2" id="like_check_1" data-toggle="tooltip" data-placement="top" title="I like it"></i>
<i onclick="like_post(this)" class="fas fa-heart float-right p-1 my-1 mr-3" data-id="3" id="like_check_2" data-toggle="tooltip" data-placement="top" title="I like it"></i>
<i onclick="like_post(this)" class="fas fa-heart float-right p-1 my-1 mr-3" data-id="4" id="like_check_3" data-toggle="tooltip" data-placement="top" title="I like it"></i>
<i onclick="like_post(this)" class="fas fa-heart float-right p-1 my-1 mr-3" data-id="5" id="like_check_4" data-toggle="tooltip" data-placement="top" title="I like it"></i>

but it is not working this is my php code for the ajax request

if (isset($_POST['comment_check'])) {
  $get_comment_id = mysqli_real_escape_string($con, test_input($_POST['comment_check']));
  $get_user_id = $_SESSION['user_id'];
  $commentcheck = mysqli_query($con, "SELECT * FROM `comment_like` WHERE `liker_id` = '$get_user_id' AND`comment_id` = '$get_comment_id' AND liked='Y'") or exit(mysqli_error($con));
if(mysqli_num_rows($commentcheck)>0){
    echo "ok";
}else{
    echo "unliked";
}

}

  • 2
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 01 '20 at 22:48
  • 1
    why issue 5 ajax requests when you could easily use a single query? – Professor Abronsius Aug 01 '20 at 22:54
  • @ProfessorAbronsius how can i use a single query for the ajax – Yusuf Obafemi Aug 01 '20 at 22:57

1 Answers1

0

As I really do not use jQuery it would be folly to try to answer the question using it and thus making mistooks so understand that is why I answer here with vanilla Javascript. Not knowing the table schema, what the function like_post does or how somebody can unlike something all pose questions but making certain assumptions one can ignore that here.

If you modify the HTML slightly to remove the ID attributes ( which really are not required )

<i class='fas fa-heart float-right p-1 my-1 mr-3' data-id='1' data-toggle='tooltip' data-placement='top' title='I like it'></i>
<i class='fas fa-heart float-right p-1 my-1 mr-3' data-id='2' data-toggle='tooltip' data-placement='top' title='I like it'></i>
<i class='fas fa-heart float-right p-1 my-1 mr-3' data-id='3' data-toggle='tooltip' data-placement='top' title='I like it'></i>
<i class='fas fa-heart float-right p-1 my-1 mr-3' data-id='4' data-toggle='tooltip' data-placement='top' title='I like it'></i>
<i class='fas fa-heart float-right p-1 my-1 mr-3' data-id='5' data-toggle='tooltip' data-placement='top' title='I like it'></i>

Then you can collect the data-id values from the HTML elements - presumably these will not always be simply 1,2,3,4,5 but will in fact be IDs from articles or whatever from db - so could in-fact be more like 23,6,98,123,5 ( ? )

var iCol=document.querySelectorAll( 'i[data-id]' );
var ids=[];

iCol.forEach( i=>{
    ids.push( i.dataset.id )
});

With all the relevant IDs you can issue your single Ajax query to the server which will use the IDs in processing which of the things the user has previously liked. As the following is basic jQuery and only lightly modified from your original I use that here rather than using XMLHttpRequest or Fetch

$.ajax({  
    url:'comment_post.php',  
    type:'POST', 
    data:{ comment_check:ids },  // send the collected IDs
    dataType:'text',  
    success:function(json){
        json.liked.forEach( id => {
            document.querySelector('i[ data-id="'+id+'" ]').classList.add('red_heart')
        })
    }
});

The PHP script to check the db:

<?php

    session_start();
    
    if( isset( $_POST['comment_check'] ) ) {
        
        $payload=[];
        $ids=explode( ',', $_POST['comment_check'] );
        
        $sql='select `comment_id` from `comment_like` where `liker_id`=? and `liked`="Y"';
        $stmt=$con->prepare( $sql );
        $stmt->bind_param( 's', $_SESSION['user_id'] );
        $status=$stmt->execute();
        $stmt->bind_result( $cid );
        
        
        $payload['status']=$status;
        $payload['user_id']=$_SESSION['user_id'];
        $payload['liked']=[];
        
        
        while( $stmt->fetch() ){
            if( in_array( $cid, $ids ) ) $payload['liked'][]=$cid;
        }
    
        
        header('Content-Type: application/json');
        exit( json_encode( $payload ) );
    }

?>
      
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46