4
  1. I have a simple like counter code, but the changes made disappear after the page is refreshed.

  2. Why does this happen, should this be done using PHP ?

  3. How can this code be written much more efficiently, just for the knowledge anyway this is not the main question.


var like=document.getElementById("like__image");
addEventListener("click",function(){
    var likeBox=document.getElementById("like__box");
    var likeAdd=Number(likeBox.textContent)+1;
    likeBox.textContent=likeAdd;
});
11
  • 2
    Yes, you'll need PHP. Commented May 10, 2015 at 14:55
  • 2
    You'll need to use some form of persistence. That can be a database, cookies, DOM Storage, etc. Most of these have both client-side and server-side (PHP) options. Commented May 10, 2015 at 14:56
  • 1
    Php and MySQL (or some other database) are needed here. Using technologies mentioned in the "answers" below your like box won't be visible to anyone but the liker. Commented May 10, 2015 at 15:00
  • 1
    You still need javascript for the events. Then you use AJAX to send data to the server, process with PHP and store with MySQL. Then you can reload your like count with php on page load and do it all over again. At least that's one very common way of managing this. Commented May 10, 2015 at 15:51
  • 1
    AJAX is the jQuery method of doing an XMLHttpRequest (XHR) Commented May 10, 2015 at 18:17

3 Answers 3

3

According to my understanding, you need this count to be global and to be available to all the users who access your page. Javascript is a client side script and the only file you can create using this is a cookie. In this case, you can't use cookies as it is created separately for each user.

For persistent result use a database or if you are not using a database for your application/website you can use a file (like .txt or .xml) to save your count and next time you can read from that file to display it again. But generally using database is recommended over a file system.

Using file system:

For main file we have a small php code to get the existing like count and an ajax function requesting like.php file when a user clicks on the like button.

HTML body:

<?php
    $likeFile = 'like.txt';
    /* check if the like file exists*/
    if(file_exists($likeFile)) {
        /* read the only the first file of the file as we don't intend to have more */
        $file = fopen($likeFile, 'r');
        $like = fgets($file);
        fclose($file);
        if($like) {
            /* if we get the line split the string "likes=number" and get the existing count */
            $likeCount = end(explode('=', $like));
        }
    } else {
        $likeCount = 0;
    }
?>
<a href="javascript:void(0)" onclick="like()">Like <span id="count"><?php echo $likeCount ?></span></a>

Javascript:

<script type="text/javascript">
function like(){
    $.ajax({
        type:"POST",
        data: {like:true},
        url: "like.php",
        success: function(result){
            $('#count').text(result);
        }
    });
}
</script>

In the like.php, we are checking for the post variable "like" just to be sure that we don't simply increment the like on direct access to this file. Here we are checking if the like.txt file exists or not. If true, it gets the first line like=1, get the count, increment the count and return it back to the ajax request. If false, it simply creates the file like.txt with like=1 for the first and only time.

<?php
if(isset($_POST['like']) && $_POST['like'] == true)
{
    $likeFile = 'like.txt';
    /* check if the like file exists*/
    if(file_exists($likeFile)) {
        /* read the only the first file of the file as we don't intend to have more */
        $file = fopen($likeFile, 'r');
        $like = fgets($file);
        fclose($file);
        if($like) {
            /* if we get the line split the string "likes=number" and get the existing count */
            $likeCount = end(explode('=', $like));
            $likeCount++; /* increment the count by one */
            file_put_contents($likeFile, 'likes=' . $likeCount); /* write the new count the same file and save it */
            echo $likeCount; /* return the like count to the ajax request */
        }
    } else {
    /* if file does not exist create it for the first time with count 1 */
        file_put_contents($likeFile, 'likes=1');
        echo '1';
    }
} else {
    return 'Something Wrong!';
}

Hope this is clear enough and helpful for you.

Sign up to request clarification or add additional context in comments.

1 Comment

If you dont mind Can you please show me a example for that,using a .txt file please.
1

I suggest looking to cookies if you want to keep track of information across page reloads in a simple way. If you want the information to be available to anybody other than the user who created it, you'll likely need some form of server-side persistence such as a database.

Comments

0

The javascript is reloaded when the page is reloaded, so it's natural that the changes are lost as well.

You can, however, store them permanently, either in a web service, or preferrably in localStorage. Then you can retrieve from localStorage on page load.

Using PHP probably wouldn't help without storing it somewhere.

I don't think your code could be written that much more efficient.

2 Comments

localStorage is a really bad suggestion here since his code appears to be a "Like Box" and whats the point in a like box if only one person in one browser can see their own likes?
It is persistent across page loads. LocalStorage is a good solution if that is the end game, and can serve as intermediate storage in the event that connection is lost. If it's data that should be shared, then yes, storing it in a database with remote access is the way to go. But, the question was "why is the data lost across page loads and how can I prevent it", which is what I answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.