Treedot
Treedot

Reputation: 101

Increment a value of a specific row when a link is clicked?

On this website, you can make posts with a name, title, and message (it's like a simple message board), and each posts is displayed on the page with a default rating of 0. The posts IDs are auto-incremented already and are stored in the row.

What I'm trying to do is make it so you can click the up or down arrow on a post and increase or decrease that post's rating. I have code for this now that seems sound, but it's not working and I don't know why.

Here's my "rateup" script:

<script>
    $(function () {
        $('.rateup').click(function() {
            var id = $(this).data('id');
            $.ajax({
                type: "POST",
                data: "id=" + id,
                url: "rateup.php"                               
            });
            location.reload();
        });
    });
</script>

The link you click to rate up looks like this (the rate down is identical so I don't feel the need to post it):

<a class='rateup' href='index.php' data-id=' " . $row['id'] . " ' title='vote up'>&#9650;</a>

And if it helps for reference, here's the entire PHP section where the posts are grabbed and echoed to the page (database info is censored obviously):

<?php
            $servername = "servername";
            $username = "username";
            $password = "password";
            $dbname = "posts";
            $tablename = "db_posts";

            $conn = new mysqli($servername, $username, $password, $dbname);
            if ($conn->connect_error) {
                die("failed to connect: " . $conn->connect_error); 
            }

            $sql = "SELECT id, rating, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC";
            $result = $conn->query($sql);


            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    echo "<br><div id='messageBar'><b><a class='rateup' href='index.php' data-id=' " . $row['id'] . " ' title='vote up'>&#9650;</a> ";
                    echo $row["rating"];
                    echo " <a class='ratedown' href='index.php' title='vote down'>&#9660;</a> </b>";
                    echo "Posted by <b>";
                    echo htmlspecialchars($row["name"], ENT_QUOTES, 'UTF-8');
                    echo "</b> on ";
                    echo $row["date"];
                    echo " at ";
                    echo $row["time"];
                    if (!empty($row['title'])) {
                        echo " - <b>";
                        echo htmlspecialchars($row["title"], ENT_QUOTES, 'UTF-8');
                        echo "</b>";
                    }
                    echo "<span style='float: right'>#";
                    echo $row["id"];
                    echo "</span>";
                    echo "</div><div id='messageContent'>";
                    echo htmlspecialchars($row["message"], ENT_QUOTES, 'UTF-8');
                    echo "<br><br><span id='commentLink'><a class='noStyle' href=''>reply to this post&nbsp;</a></span>";
                    echo "<br></div><br><hr>";
                }
            } else {
                echo "<br>";
                echo "<center><i>it's dusty in here</i></center>";
                echo "<br>";
            }

            $conn->close();
        ?>

And lastly, this is the rateup.php file:

<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "posts";
$tablename = "db_posts";

// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1) WHERE id = ' ".$id." ' ");

mysqli_close($connection);

echo 'OK';     ?>

If anyone can help with this I would greatly appreciate it, I've been trying to figure it out myself for the last two days, so this is my only hope right now.

Upvotes: 0

Views: 206

Answers (1)

omerts
omerts

Reputation: 8838

You are refreshing the page before the ajax request has completed, this causes the request to cancel: enter image description here

Look at your network tab in the browser's developer tools. If you are refreshing, you might as well not use AJAX. Just send a post to the page, and get the updated results.

Update to answer comment

Two possibilities are:

1) Making the up/down votes as form buttons (styling them as needed), and send a post your php file, which will process the rate up/down, and return an updated html view.

2) Don't refresh after the ajax call (also change the href in the link so it doesn't cause a refresh either). In your ajax success function, if you received an 'OK' response from rateup.php, manually change the vote up/down. (Preferable solution)

So:

<script>
    $(function () {
        $('.rateup').click(function() {
            var id = $(this).data('id');
            $.ajax({
                type: "POST",
                data: {id: id}, // In es2015 data: {id}
                url: "rateup.php",
                success: function(result) {
                    if (result === 'OK') {
                        var voteContainer = $(locate_the_element_with_the_vote_count);
                        var newVoteCount = parseInt(voteContainer.text()) + 1;
                        voteContainer.text(newVoteCount)
                    }
                }
            });
        });
    });
</script>

And to stop link from refreshing:

<a class='rateup' href='javascript:;' data-id=' " . $row['id'] . " ' title='vote up'>&#9650;</a>

Upvotes: 1

Related Questions