0

I am creating a feature for users to be able to like a status, and once liked, it will change from a thumbs up icon to "liked!"

The problem I am having is that I'm using this in a while loop, and when I like one status (lets say 2nd row), then I go to like another status (lets say 3rd row), it will show the "liked!" result only on the 2nd row. I want it to show "Liked!" on both rows when clicked. The database receives the correct information from the different rows, I just want the results to reflect on the different rows as well.

Here's my code below:

<?php
if(isset($_SESSION['id'])) {

$sql = "SELECT * FROM user_status WHERE (userid = '$statusposterid') AND (statusid = '$statusid') ";
$result0 = mysqli_query($conn, $sql);
if (mysqli_num_rows($result0) > 0) {
    while ($row = mysqli_fetch_array($result0)) {

    $statusid = $row['statusid'];
    $likerid = $_SESSION['id'];

    $sql = "SELECT * FROM user_likes WHERE likerid='$likerid' AND likesid='$statusid'";
    $result = mysqli_query($conn, $sql);
    $alreadylike = mysqli_num_rows($result);
    if (!$alreadylike > 0) {

    $sql3 = "SELECT * FROM user_likes WHERE likesid='$statusid'";
    $result3 = mysqli_query($conn, $sql3);
    $likecount = mysqli_num_rows($result3); 
?>      

    <td style="width: 100px;">  
    <p align="center">
<div id="contact_form">
<form name="likestatus" action="">
  <fieldset>
    <input type="hidden" name="likesid" id="likesid" size="30" value="<?php echo $statusid ?>" class="text-input" />

    <input type="hidden" name="likerid" id="likerid" size="30" value="<?php echo $_SESSION['id']; ?>" class="text-input" />

      <br />

        <button style="width: 100%; border: none; background:none!important; background-color: transparent; cursor: pointer;" type="submit" name="likestatus" class="button" id="submit_btn">
        <i class="fa fa-thumbs-o-up fa-fw ss-large ss-text-grey"></i>
        </button>   

  </fieldset>
</form>

</div>

    <font><?php echo $likecount; ?> likes</font>
    </td>   

<?php
    }
    }
}
}
?>                              

<script>
  $(function() {
    $(".button").click(function() {
      // validate and process form here
    });
  });
</script>


<script>
  $(function() {
    $('.error').hide();
    $(".button").click(function() {
      // validate and process form here

      $('.error').hide();
      var likesid = $("input#likesid").val();
        if (likesid == "") {
        $("label#likesid_error").show();
        $("input#likesid").focus();
        return false;
      }
        var likerid = $("input#likerid").val();
        if (likerid == "") {
        $("label#likerid_error").show();
        $("input#likerid").focus();
        return false;
      }


  var dataString = 'likesid='+ likesid + '&likerid=' + likerid + '&likestatus=' + likestatus;
  //alert (dataString);return false;
  $.ajax({
    type: "POST",
    url: "simpletest.php",
    data: dataString,
    success: function() {
      $('#contact_form').html("<div id='message'></div>");
      $('#message').html("<h3>Liked!</h3>")
      //.append("<p>We will be in touch soon.</p>")
      .hide()
      .fadeIn(1500, function() {
        $('#message').append("");
      });
    }
  });
  return false;   

    });
  });
</script></p>

Do I have to change the order of my code? I looked everywhere I could to find this solution but so far, no luck. Keep in mind that I am extremely new to javascript.

Edit:

From more research, it looks like I need to set different ID's for the form somehow. I am not sure exactly which field I need to add a different id in, I've tried all different ways I could think of and have yet to achieve my desired result.

NEW CODE EDIT:

    <?php
if(isset($_SESSION['id'])) {



$sql = "SELECT * FROM user_status WHERE (userid = '$statusposterid') AND (statusid = '$statusid') ";
$result0 = mysqli_query($conn, $sql);
if (mysqli_num_rows($result0) > 0) {
    while ($row = mysqli_fetch_array($result0)) {

    $statusid = $row['statusid'];
    $likerid = $_SESSION['id'];

    $sql = "SELECT * FROM user_likes WHERE likerid='$likerid' AND likesid='$statusid'";
    $result = mysqli_query($conn, $sql);
    $alreadylike = mysqli_num_rows($result);
    if (!$alreadylike > 0) {

    $sql3 = "SELECT * FROM user_likes WHERE likesid='$statusid'";
    $result3 = mysqli_query($conn, $sql3);
    $likecount = mysqli_num_rows($result3); 
?>      

    <td style="width: 100px;">  
    <p align="center">
<div class="contact_form">
    <fieldset>
        <!-- removed id attribute -->
        <input type="hidden" name="likesid" size="30" value="<?php echo $statusid ?>" class="text-input" />
        <input type="hidden" name="likerid" size="30" value="<?php echo $_SESSION['id']; ?>" class="text-input" />
        <br />
        <!-- removed id attribute -->
        <!-- replaced type attribute as you are not submitting really -->
        <button style="width: 100%; border: none; background:none!important; background-color: transparent; cursor: pointer;" type="button" name="likestatus" class="button"><i class="fa fa-thumbs-o-up fa-fw ss-large ss-text-grey"></i></button>
    </fieldset>
</div>

    <font><?php echo $likecount; ?> likes</font>
    </td>   

<?php
    }
    }
}
}
?>                              

<script>
$(function() {
    // get into the habit of caching the elements you will be re-using
    var error = $('.error');

    $('.button').click(function () {
        error.hide();

        // cache all the elements we'll be using
        var contactForm = $(this).closest('.contact_form'),
            likesid = contactForm.find('input[name=likesid]'),
            likerid = contactForm.find('input[name=likerid]');
            likestatus = contactForm.find('button[name=likestatus]');

        if (likesid.val() == '') {
            // ...
            likesid.focus();
            return false;
        } 
        if (likerid.val() == '') {
            // ...
            likesid.focus();
            return false;
        }

        // easier to use object rather than string
        // not sure where likestatus came from so it is ommitted
        var data = { likesid: likesid.val(), likestatus: likestatus.val(), likerid: likerid.val() };

        // short-hand method for $.ajax with POST
        $.post('simpletest.php', data, function (res) {
            // the rest
        });

        // no need to do any return false
    });
});
</script></p><br>                               

1 Answers1

1

It's hard to tell what your problem is, but as I mentioned in my comment, you can't have multiple elements with the same ID. Start by removing your IDs (or replacing them with classes).

Here's a template (untested) on how things should look to an extent.

HTML

<!-- replaced id attribute with class attribute -->
<div class="contact_form">
    <fieldset>
        <!-- removed id attribute -->
        <input type="hidden" name="likesid" size="30" value="<?php echo $statusid ?>" class="text-input" />
        <input type="hidden" name="likerid" size="30" value="<?php echo $_SESSION['id']; ?>" class="text-input" />
        <br />
        <!-- removed id attribute -->
        <!-- replaced type attribute as you are not submitting really -->
        <button style="width: 100%; border: none; background:none!important; background-color: transparent; cursor: pointer;" type="button" name="likestatus" class="button"><i class="fa fa-thumbs-o-up fa-fw ss-large ss-text-grey"></i></button>
    </fieldset>
</div>

You'll notice I removed the <form> tag because you don't really need it in your case as you are using AJAX.

JavaScript

$(function() {
    // get into the habit of caching the elements you will be re-using
    var error = $('.error');

    $('.button').click(function () {
        error.hide();

        // cache all the elements we'll be using
        var contactForm = $(this).closest('.contact_form'),
            likesid = contactForm.find('input[name=likesid]'),
            likerid = contactForm.find('input[name=likerid]');

        if (likesid.val() == '') {
            // ...
            likesid.focus();
            return false;
        } 
        if (likerid.val() == '') {
            // ...
            likesid.focus();
            return false;
        }

        // easier to use object rather than string
        // not sure where likestatus came from so it is ommitted
        var data = { likesid: likesid.val(), likerid: likerid.val() };

        // short-hand method for $.ajax with POST
        $.post('simpletest.php', data, function (res) {
            // the rest
        });

        // no need to do any return false
    });
});

Useful links:

Mikey
  • 6,728
  • 4
  • 22
  • 45
  • Okay, we're making progress but now I'm missing one of the main things. Without the likestatus variable, the code wasn't working. I added it in and now the post sends the correct information to the database, but I no longer have a result echo'd back into the div saying "Liked!". – sicksixstrings Jun 20 '17 at 19:50
  • @sicksixstrings Edit your question with your new code. – Mikey Jun 20 '17 at 19:51
  • I've just added the new block of code I am working with – sicksixstrings Jun 20 '17 at 19:55
  • 1
    @sicksixstrings You need to put code in the `// the rest` part. That is your previous `success` handler. Also you no longer have `contact_form` as an ID but as a class. You should use `contactForm` that cached so something like `contactForm.html('

    Liked

    ')` with the rest.
    – Mikey Jun 20 '17 at 19:58
  • You're a legend, a hero, and a life saver. Thank you so much for your effort in helping me solve this! It works flawlessly now. – sicksixstrings Jun 20 '17 at 20:22
  • If you don't mind, I have one more question if you may could assit. If I am wanting to use this same code more than once on my page, what in the code do I need to change? Is it the name, class or id perhaps? I am already using a different name for this new button (unlike). – sicksixstrings Jun 21 '17 at 04:05