0

I have created a blog in php. For each comment the user can press a Favorite/Unfavorite button (if want) to Favorite/Unfavorite a post. My button works perfect. The only problem I got is that when user press Favorite/Unfavorite... I dont get the number of Favorites/Unfavorites for this post. In order to get this, each time I have to refressh the page. Some people told me that I need to use Ajax in order to do this.

I use table likes, to hold favorites for each post: likes(like_id, user, the_comment_id) I use table comments for aeach post: comments(comments_id, comment, user)

This is my php code:

<?php

$comment_id = $row['comments_id'];

// ... code above

//button for favorite and unfavorite
 $get_button = mysql_query(" SELECT * FROM `likes` WHERE `user`='$session_user_id' AND `the_comment_id`='{$row['comments_id']}'  ");                    
 $get = mysql_fetch_assoc($get_button);

if($get==""){   
    $comments .= "<a role='button' class='button' id='like$comment_id'  style='color:grey;'>Favorite</a>";
}else if($get!=""){
    $comments .= "<a role='button' class='button' id='unlike$comment_id' style='color:grey;'>Unfavorite</a>";
}

// place favorites for this comment here
$comments .= " $total_favorites ";

?>

This is my jquery:

<script>

$(document).ready(function(){
$("#like<?php echo $comment_id; ?>").click(function() { 
  var id = "<?php echo $comment_id; ?>";
  $.post("parse.php",{like:id}, function(data){

   $("#like<?php echo $comment_id; ?>");
   $(".button<?php echo $comment_id; ?>").html(data);

  });
  $(this).hide().attr("Disabled", "True").text("Favorite done!").show();
});


$("#unlike<?php echo $comment_id; ?>").click(function() { 

  var id = "<?php echo $comment_id; ?>";
  $.post("parse.php",{unlike:id}, function(data){

   $("#unlike<?php echo $comment_id; ?>");
   $(".button<?php echo $comment_id; ?>").html(data);

});     
$(this).hide().attr("Disabled", "True").text("Unfavorite done!").show();
 });

});

</script>

This is my parse.php code:

<?php  

if(isset($_POST['like'])){
 $id = $_POST['like'];      
  mysql_query("INSERT INTO likes VALUES ('', '$session_user_id', '$id') "); 
}


if(isset($_POST['unlike'])){
 $id = $_POST['unlike'];
 mysql_query(" DELETE FROM likes WHERE `user`='$session_user_id' AND `the_comment_id`='$id'  ");
}


$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}'  ");    
$total_favorites = mysql_num_rows($favorites);

?>
user2491321
  • 673
  • 10
  • 32

4 Answers4

2

You would need to return something from the parse.php script. The data variable will not contain the count unless you either echo it out directly or return JSON and parse in your jQuery function prior to setting the .html(data) values.

Lucas
  • 51
  • 3
  • any idea how to do this? – user2491321 Mar 13 '14 at 19:58
  • See the examples attached to answer below: just use **echo**. For example, write: `echo "Found " . $total_favorites . " favorites in the database.";` – cssyphus Mar 13 '14 at 20:02
  • 1
    Or, better yet, create a variable containing all the code you wish to return: `$out = "

    Favs

    Found " .$total_favorites. "favorites"; echo $out;`

    – cssyphus Mar 13 '14 at 20:04
1

You are right, AJAX is the way to go. Note that AJAX is known by multiple names:

  • XMLHttpRequest -- javascript
  • AJAX
  • $.ajax() -- the jQuery superset
  • $.get() -- a shortcut to $.ajax() with TYPE: "GET"
  • $.post() -- a shortcut to $.ajax() with TYPE: "POST"
  • $.load() -- see Difference between $("#id").load and $.ajax?

Here are some examples that will get you started on AJAX:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
1

Further to what Lucas said, change your code to look like this:

<?php  

    if(isset($_POST['like'])){
        $id = $_POST['like'];      
        mysql_query("INSERT INTO likes VALUES ('', '$session_user_id', '$id') "); 
    }

    if(isset($_POST['unlike'])){
        $id = $_POST['unlike'];
        mysql_query(" DELETE FROM likes WHERE `user`='$session_user_id' AND `the_comment_id`='$id'  ");
    }

    $favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}'  ");    
    $total_favorites = mysql_num_rows($favorites);
    
    $out = '<h1>Found In Database</h1>';
    $out .= '<p>You received ' .$total_favorites. ' favorites.';

    echo $out;
?>
halfer
  • 19,824
  • 17
  • 99
  • 186
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • thats ok i understant what is have to change in my parse php file. Any idea how to change now my jquery script and how to add ajax inside it? – user2491321 Mar 13 '14 at 20:22
  • You are using AJAX -- $.post() is AJAX. However, I will look again at your code. – cssyphus Mar 13 '14 at 20:24
  • @user2491321 I created another answer for the revised jQuery code – cssyphus Mar 13 '14 at 20:37
  • A quick heads up for readers: this code contains SQL injection vulnerabilities, and is dangerous to use. It looks like it was copied from the original post. Always use parameter binding when accessing a relational database, unless it is unavailable, in which case untaint or escape values with care. – halfer May 09 '21 at 10:23
0

If this doesn't work, then please post the relevant HTML so that we can accurately target your DOM elements:

$(document).ready(function(){

    $("[id^=like]").click(function() { 
        var window.id = $(this).attr('id').split['e'][1];
        $.post("parse.php",{like:id}, function(data){
            $("#like"+id).find(".button").html(data);
        }); //END .post
        $(this).hide().attr("Disabled", "True").text("Favorite done!").show();
    }); //END like.click


    $("[id^=unlike]").click(function() { 
        var window.id = $(this).attr('id').split['e'][1];
        $.post("parse.php",{unlike:id}, function(data){
            $("#unlike"+id).find(".button").html(data);
        }); //END .post
        $(this).hide().attr("Disabled", "True").text("Unfavorite done!").show();
    }); //END #unlike.click

});

Notes:

  1. We use $("[id^=unlike]") as the selector - this means: get the DOM element with an ID that starts with "unlike"

  2. $(this).attr('id').split['e'][1] means:
    a. Get the ID attribute ("like5" or "unlike123")
    b. Break it into an array at teh 'e' char: lik and 5 -or- unlik and 123
    c. Grab the 2nd array element (the number: 5 or 123)
    d. Stick it in a global variable called id

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • my only html code for button I use are at the top of code posted in my main php file: Favorite and Unfavorite – user2491321 Mar 13 '14 at 20:49
  • In your first php code block, you are building a PHP variable called `$comments` - but you never echo it out the screen. How does it appear on the screen? If it does not, then just do `echo $comments;` to see it on screen. – cssyphus Mar 13 '14 at 21:34
  • ok yes you are right. $comments .=".$row['comment']."; it gets the row of comment from table comments. – user2491321 Mar 14 '14 at 14:19