2

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.

ola.rogula
  • 307
  • 1
  • 9
  • You can't use PHP to handle the buttons else it refreshes the page. – KANAYO AUGUSTIN UG May 04 '16 at 22:25
  • PHP executes server-side, and the result is sent as an HTTP stream to the client (the user's browser). AJAX and jQuery live in the browser (client-side), and interaction with the srver is done through the XMLHTTPREQUEST object. Here's a good starting point: http://www.webmonkey.com/2010/02/ajax_for_beginners/ – Webomatik May 04 '16 at 22:33
  • @Webomatik hey thanks, that's actually a decent read. But like, I'm already lost.. when they start writing the javascript functions, where in the code is that? On what file? – ola.rogula May 04 '16 at 22:59

2 Answers2

2

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

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Hey, thanks a lot! I'm trying to implement this staying as close as I can. There's only gonna be one game to like per page, and yes, each has a unique #id which I have. And in the database I need to input or delete the gameid and userid pair. I'm trying to make the edits now.. – ola.rogula May 05 '16 at 16:47
  • ..I think I've pretty much got it working.. just having trouble making it connect to the database.. – ola.rogula May 05 '16 at 17:43
  • Okay sweet, it's working! I'm getting some "session cache limiter" errors but that's probably specific to my weird site haha. The only thing now would be how to make the button switch dynamically once the database is updated (ideally I want only the relevant button to show up.. Like This if you haven't liked it yet, and vice versa). – ola.rogula May 05 '16 at 18:09
  • Okay, errors sorted.. so exciting! So is the magic now in the "success" bit of that ajax function? Can I make that do stuff, like, switch the button from Like to Unlike? =O – ola.rogula May 05 '16 at 19:52
  • Yes, you got it. Anything ECHO'd by the PHP file will be received in the `success` function as (`d` in my example). Based on what comes back you can switch the button from like to unlike. To keep the first answer from getting unreadable, I put some sample code in another answer. Play with the jsFiddle and see how it works. *The purpose of the `animate` code is to replace the ajax, so that the variable must be available in another function.* – cssyphus May 06 '16 at 02:08
1

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

cssyphus
  • 37,875
  • 18
  • 96
  • 111