简体   繁体   中英

Simple Like/Unlike text button - adding ajax etc

I'm trying to make a very simple Like/Unlike button in PHP (where the page does NOT refresh) I know there are countless tutorials on this but because I am completely new to ajax & jquery, I can't figure out how to implement them (in what file does which part of the code go etc). I have a database of userid's and a new database of user likes. I've gotten this far:

<?php
if (!loggedin())    {
    echo 'Please login or register to fave games';
} else {
    $gameNum = $GAMES_REPOSITORY[$this_game][num];
    $qry = mysql_query("SELECT * FROM fave_games WHERE gamenum='".$gameNum."' AND userid='".$_SESSION[userID]."'");
    if (mysql_num_rows($qry)==0)    {
        # print button to fave
        echo 'You haven\'t liked this';     

    } else  {
        # print button to unfave
        echo 'You\'ve liked this';

    }
}
?>

This works, and it manages to check if the user has liked the page/game before or not. And I know I can figure out the last steps, which would be inserting or deleting the like/unlike into the database. I just can't figure out the middle bit, where ajax and jquery come in to make the text buttons and where to code their function... Any help would be greatly appreciated.

Let's suppose you have two buttons: Like and Unlike. Ideally, you also will be able to store the gameID with the button, something like this:

<button id="L-17" class="likers">Like PacMan</button>
<button id="U-17" class="likers">Un-like PacMan</button>

more code goes here

<button id="L-18" class="likers">Like Tetris</button>
<button id="U-18" class="likers">Un-like Tetris</button>

Your code for the like/dislike will be something like this:

<script type="text/javascript">
    $(function(){
        $(document).on('click', 'button.likers', function(){
            like_type = this.id.split('-')[0]; //L or U
            like_val  = this.id.split('-')[1]; //17 (Pacman) or 18 (Tetris)
            $.ajax({
                type: 'post',
                 url: 'another_php_file.php',
                data: 'lt=' +like_type+ '&lv=' +like_val,
                success: function(d){
                    if (d.length) alert(d);
                }
            });
        }); //END button.likers click
    }); //end document.ready
</script>

another_php_file.php:

<?php
    $lt = $_POST['lt'];
    $lv = $_POST['lv'];
    $like_status = ($lt == 'L') ? 1 : 0 ;
    $pseudo_query = "UPDATE `fave_games` SET 'game_liked' = '$like_status' WHERE `game_num` = '$lv' "

    echo 'Submitted a ' . $lv;

Notes:

  1. The javascript/jQuery code can be added in the document just before the </body> tag.

  2. You need a separate file for the AJAX PHP code. Here's why . It is possible to use the same AJAX PHP file for multiple AJAX calls and send an extra variable that identifies the AJAX call to be processed.

  3. Anything ECHOd by the PHP AJAX file will be available in the jQuery AJAX success function. In my sample code, it appears in a variable called d

  4. This answer contains some simple AJAX examples that might help get the hang of AJAX. I recommend copying the complete example and making it work on your own server. Those fifteen or twenty minutes will save you HOURS.

AJAX request callback using jQuery

To switch the button say like/unlike:

<script type="text/javascript">
    var like_type, like_val; //declare outside fns to make global
    $(function(){
        $(document).on('click', 'button.likers', function(){
            like_type = this.id.split('-')[0]; //L or U
            like_val  = this.id.split('-')[1]; //17 (Pacman) or 18 (Tetris)
            $.ajax({
                type: 'post',
                 url: 'another_php_file.php',
                data: 'lt=' +like_type+ '&lv=' +like_val,
                success: function(d){
                    if (d.length) alert(d);
                    $('#' +like_type+ '-' +like_val).text('Different text');
                }
            });
        }); //END button.likers click
    }); //end document.ready
</script>

 var btn; $('#b17').click(function(){ btn = this.id; $(this).animate({ 'font-size': '30px' },500,function(){ $('#' + btn).text('Bonjour'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="b17">Like</button> 

jsFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM