Home > database >  problem to print result after ajax success
problem to print result after ajax success

Time:06-27

Please help to fix this issue with like counting. i create a news feed like facebook using php mysql and ajax.

problem is that when i click on like button it prints like count from (this value) and showing to all, let say i have 5 posts and like current value for different posts are 100, 200 , 70 , 80 , 578. when I click on first post ajax success count 100 1 = 101 for first post and for all other post printting same 101 likes. now if i will go to 2nd post and its like value 200, ajax will show 200 1 =201 like. so after click on 2nd post all 5 posts like will show 201. its creating problem for me. I understand that after ajax success i mentioned to show the value to div class (.ajax_like_result), thats why its showing in every post, same result until i am not clicking on different post.
how to fix this so that when I click on any post it wil show only its real like value??

I try to change the DIV attribute id , instead of class then it only works for first post. other post totally not working. if i set div atribute to class then like is working but printing incorrectly as i mentioned above.

I have pasted below- html , php and ajax code . thanks for your help.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $('.ajax_like').on('click', function () {
        var post_id = $(this).val(); 
        var page = $(this).attr("data-id"); 
        
        $.ajax({
           type: 'POST',
           url: 'like.php',
           data: {post_id:post_id, page:page},
       dataType: 'json',      
          // cache: false,
           success: function(data){                
                $(".ajax_like_result").html(data);              
                }
        });
    });
});
</script>


html : 
<li  type="submit"  name="data-id" data-id="<?php echo $page;?>" value="<? echo $post_id;?>">                         
               <div class= "ajax_like_result" ><?php print $likes;?></div>
             
    </li>


like.php code :

<?php //user info start
session_start();
$conn=mysqli_connect("localhost", "u1068033_ab24", "ab@24", "u1068033_ab24");
mysqli_set_charset($conn,"utf8");

$id=$_SESSION['id'];


$get_post_id = $_POST['post_id'];

$page = $_POST['page'];
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
$likes=$row['likes'];
$sql="UPDATE $page SET `likes`=$likes 1 WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
echo $row['likes'];`enter code here`

?>

CodePudding user response:

you are writing the result to all HTML elements with the same class "ajax_like_result" when using this line: $(".ajax_like_result").html(data);

you can use something such as:

$("li[data-id='" page "'] div.ajax_like_result").html(data);

Also better using native JavaScript and not jQuery, using document.querySelector

document.querySelector(`li[data-id='${page}'] div.ajax_like_result`).innerHTML = data;

and replace the jQuery AJAX with the native JavaScript fetch

example in one piece of code block with native JavaScript (no need for jQuery):

document.addEventListener("DOMContentLoaded", (event) => {
  document.querySelectorAll('li[data-id]').forEach((elem)=>{
    elem.addEventListener('click', event => {
      const domElem = event.target;
      const postId = domElem.getAttribute('value');
      const page = domElem.getAttribute('data-id');
      const data = {post_id:postId, page:page};

      console.log({data});

      fetch('links.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
        })
        .then(response => response.json())
        .then(data => {
          console.log('Success:', data);
          const selector = `li[data-id='${page}'] div.ajax_like_result`;
          document.querySelector(selector).innerHTML = data;
        })
        .catch((error) => {
          console.error('Error:', error);
      });
    });
  });
});

and better also to remove from the PHP code the '?>' as the PHP ends the script execution at the end and it will reduce some possible unwanted white spaces.

CodePudding user response:

You should need some corrections on your jQuery

$(document).ready(function(){

$('.ajax_like').each( function(){

    $(this).on('click', function () {
    var post_id = $(this).val(); 
    var page = $(this).attr("data-id"); 
    
    $.ajax({
       type: 'POST',
       url: 'like.php',
       data: {post_id:post_id, page:page},
   dataType: 'json',      
      // cache: false,
       success: function(data){                
            $(this).find(".ajax_like_result").html(data);              
            }
    });
});
    
})

});

  • Related