-2

I am trying to make a like/dislike system on the posts of my social networking website with each post having an pid(auto-increment). I run a while loop that fetches the post from database and show it and also give an option to like/dislike below each post. I am not using any input radio or checkbox button, instead I have used an icon for which the colour should change when clicked and also an AJAX function is called using onclick event on the same icon.

The AJAX function should go to a file likes.php where the a search is done for the row having that post id and the likes column of that row is updated or incremented by 1 and then the result is returned by echo. All this should work but not working.

The AJAX function takes post id (pid) as a parameter and pass it to likes.php where likes field corresponding to that post id is incremented. The like icon for each post has been assigned an id = post id so as to select that like button which is clicked and for which the post id is passed in AJAX function. The result is returned to a span element having an id = "like"+ post pid.

My code

index.php - to show posts and like button

$q = $conn->prepare("SELECT * FROM posts ORDER BY pid DESC");
$q->execute();

while($row = $q->fetch(PDO::FETCH_ASSOC)) {
#my post representation using div and all...

#like/dislike button
  <span class=\"right floated\" id=\"like".$row['pid']."\" >
<i id=\"".$row['pid']."\" class=\"heart icon\"       onclick=\"like(".$row['pid'].")\"></i>

     </span>

          }

ajax-function 'a' is a parameter-local variable

<script>
              $(document).ready(function(){
                  function like(a) {
                  $("#"+a).css('color','red');
                    $.ajax({
                     url: "likes.php",
                       data: ({pid: a}),
                   type: "POST",
                     success:function(data){
                       $("#like"+a).html(data);
                       },
                     error:function (){}
                        });
                     }
                    });
                  }
               </script>

likes.php file

                <?php
           session_start();
            include 'db.php';



           $j =$_POST['pid'];

             $sql = "UPDATE posts SET likes = likes +1 WHERE pid ='" . $j . "'";
            $r = $conn->prepare($sql);
           $r->execute();

         $sql = "SELECT * FROM posts WHERE pid ='" . $j . "'"; 
        $r = $conn->prepare($sql);
        $r->execute();
         $ry=$r->fetch();
        if($r)
            {
       echo $ry['likes'];
           }


      ?>

Please tell me why doesn't it work; at least it should detect the icon click using onclick but I think even that's not working. The AJAX function is not getting executed as nothing happens on clicking.

halfer
  • 18,701
  • 13
  • 79
  • 158
Zaki Mustafa
  • 147
  • 11
  • Are there any errors pop out on browser console? – Chay22 Jun 23 '16 at 14:26
  • no..actually when i click nothing happens .i think the function is not even called ..atleast if a call had been made, may be i would have got an error but nothing is hapening – Zaki Mustafa Jun 23 '16 at 14:30
  • @ZakiMustafa you've probably messed it up with the quotes in the index.php – postrel Jun 23 '16 at 14:32
  • no..i dont think so.let me check..the span element is under an echo statement echo " "; like this.. – Zaki Mustafa Jun 23 '16 at 14:33
  • Just a side note, [`click` is better than `onclick`](http://stackoverflow.com/questions/12627443/jquery-click-vs-onclick) – Chay22 Jun 23 '16 at 14:37

1 Answers1

0

The problem here, that you declare the like function inside the document ready so outside of that scope your function is not defined.

Posible solutions:

  • Declare your function before the document ready scope
  • Create a var outside of document ready
  • Use jQuery .click (or .on('click',) instead of the onClick html property to call your function

Declare your function before the document ready scope

script:

function like(a) {
    $("#" + a).css('color','red');
    $.ajax({
        url: "likes.php",
        data: {pid: a},
        type: "POST",
        success:function(data){
            $("#like" + a).html(data);
        },
        error:function (){}
    });
}

Create a var outside of document ready

var like;
$(document).ready(function(){
    like = function(a) {
        $("#" + a).css('color','red');
        $.ajax({
            url: "likes.php",
            data: {pid: a},
            type: "POST",
            success:function(data){
                $("#like"+a).html(data);
            },
            error:function (){}
        });
    }
});

(This can cause some problem, because until the document is not ready this function not gonna work)

Use jQuery .click (or .on('click',) instead of the onClick html property to call your function

index.php

<span class=\"right floated\" id=\"like".$row['pid']."\" >
    <i id=\"".$row['pid']."\" class=\"heart icon action-like\"></i>
</span>

script

$('.action-like').on('click', function(){
    var pid = $(this).attr('id');

    $("#" + pid).css('color','red');
    $.ajax({
        url: "likes.php",
        data: {pid: pid},
        type: "POST",
        success:function(data){
            $("#like" + a).html(data);
        },
        error:function (){}
    });
});

This should work. But use mysqli instead mysql and do not pass parameters to a query like you do (read about sql injection). And do not echo long static strings instead close php tag and open when needed to echo out a dynamic data.

Nergal
  • 855
  • 1
  • 12
  • 26
  • i removed document ready..but if i use .click , how woud i know which post's icon is clicked and how wud i pass the post's id to likes.php – Zaki Mustafa Jun 23 '16 at 14:48
  • thanks ..i am gonna try this but what do you mean by this statement "The can cause some problem"? – Zaki Mustafa Jun 23 '16 at 15:15
  • @ZakiMustafa Sorry I just mispelled "This". And the problem this can cause is you can not call that funcion until the document becomes ready. – Nergal Jun 23 '16 at 15:49
  • I did it your way ..but still nothing happens on clicking...bcz i think there are so many likes button having same id action-like..so jquery gets confused!!! Maybe – Zaki Mustafa Jun 23 '16 at 15:51
  • How to call ajax function ...like this like(pid) or what? – Zaki Mustafa Jun 23 '16 at 15:54
  • @ZakiMustafa I added the ajax call. I use jQuery for a long time and it's impossible to confuse it. And also action-like is a class not an id, that's two different thing. – Nergal Jun 23 '16 at 18:00
  • Thanks Nergal..it worked but the code wast working in head section..the moment i changed it to after body position ..it worked...Thanks a lot..u really helped a lot – Zaki Mustafa Jun 24 '16 at 02:26
  • @Nergal sir i have a similar problem like this but instead of `like` i want to `share icon` to `share on facebook , whatsapp, etc` by jquery ajax, so give me basic idea about that. – KUMAR Jul 21 '20 at 11:57