最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to make changes to HTML document permanent using Javascript? - Stack Overflow

programmeradmin2浏览0评论
  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;
});
  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;
});
Share Improve this question asked May 10, 2015 at 14:53 CoDINGinDARKCoDINGinDARK 3464 silver badges17 bronze badges 11
  • 2 Yes, you'll need PHP. – Firedrake969 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. – Jonathan Lonowski 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. – You Old Fool 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 mon way of managing this. – You Old Fool Commented May 10, 2015 at 15:51
  • 1 AJAX is the jQuery method of doing an XMLHttpRequest (XHR) – You Old Fool Commented May 10, 2015 at 18:17
 |  Show 6 more ments

3 Answers 3

Reset to default 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 remended 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.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论