How to storing likes and dislikes in a json file

Updated: 05-Jan-2023 / Tags: PHP and AJAX / Views: 643 - Author: George

Introduction

We are going to create a like and dislike system with PHP and JavaScript. But instead of storing the likes or dislikes in the database we are going to store them in a json file.

Let's see how we are going to do this.

In the image bellow you see what we are going to code.

Image of an article with like and dislike icons

Let's start from the project's folder and see what files we need.

Project's folder

We need to create in the localhost server's directory the following files:

  • An index.php file. This is our home page in which we are going to have an article and the thumbs-up and thumbs-down icons.
  • A script.js JavaScript file, from which we are going to send an AJAX request to the php file.
  • A script.php file, this file will handle the AJAX request and will store the like or dislike in the json file.
  • A reactions.json file to store the likes or dislikes.
  • And last a styles.css file to make the page look pretty.
If you want the source code, scroll to the bottom of the page and click on the Get source code button, but if you want to follow along continue reading. Either way, happy coding.

Now that we have set-up our project's folder, let's start from the reactions.json file.

The JSON file

In the json file we have objects that are associated with the articles, that we want the users to react.
Every object has an "article-id" property with a unique value. We can have multiple objects in the json file, but they must have a unique "article-id" so we can target them from the php file and update the values.
Next we have a "likes" and "dislikes" property initialized with values of zero. And a "users[]" array in which we are going to store the user who likes or dislikes the article.

In our case we have two objects, the first with an "article-id" of 001.
And the second has an "article-id" of 002.

[
    {
        "article-id": "001",
        "likes": 0,
        "dislikes": 0,
        "users": []
    },
    {
        "article-id": "002",
        "likes": 0,
        "dislikes": 0,
        "users": []
    }
]    

In order to a user to like or dislike an article he has to be logged-in. So in the code that follows we are going to assume that the user is logged-in and we assign him a unique user-id. You will see when we get to the php file.

Now let's see the index file.

The index.php file

In the index file, and before we write any HTML, we are going to have a block of php code. In short in the php code we are going to grab the number of likes and dislikes from the JSON file that the article with article-id of 001 has. Which currently are 0.

<?php 
	// Usually the article's id comes from the database, 
	// but here we assign the value manually for the tutorials purpose.
	$article_id = 001;

	// We fetch the data from the json file and store them in the $data variable.
	$data = file_get_contents("reactions.json");
	
	// Next we decode the json data to an array and store them back to the $data variable.
	$data = json_decode($data, true);

	// Next we loop through the $data array ...
	foreach($data as $key => $value){
		
		// ... and search for the article's id. 
		if($article_id == $value["article-id"]){
		
			// If there is a match we fetch the likes ...
			$likes = $value["likes"];
		
			// ... and the dislikes.
			$dislikes = $value["dislikes"];
		}
	}
?>

Next we have the html code. The important stuff in here are the link to the css file in line 17, the script tags pointing to the javascript file in line 41, and the div element with a class of "reactions" from line 29 to 39.

Besides that in line 22, 23, and 25 we have the dummy article.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="styles.css">
	<title>Home page</title>
</head>
<body>
	
	<h1>How to save likes and dislikes in a JSON file</h1>	
	<h2>Introduction</h2>

	<p class="text">
		Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tempora nulla, omnis sed magnam labore a quo repellendus, illo quas tempore, reprehenderit ullam earum quae explicabo ad itaque asperiores perspiciatis qui delectus aliquam. Dolore, recusandae est neque commodi nisi ipsa nemo, expedita aliquam voluptatibus provident tempora unde, sit voluptas perspiciatis nihil ex, error eveniet aut suscipit? Eos aliquid aliquam explicabo exercitationem ab, ratione molestiae, fuga nemo porro libero architecto vero soluta earum. Doloribus voluptatibus amet, fugiat! Voluptas totam at hic quisquam harum, quis ratione, praesentium architecto vel vitae quasi itaque dolorem voluptates eius porro ipsum optio est voluptatibus, id animi, fugiat.
	</p>

	<div class="reactions">
		<div class="likes">
			<span class="likes-placeholder"><?php echo $likes ?></span>
			<span onclick="like('<?php echo $article_id ?>')" class="icons">👍</span>
		</div>
		
		<div class="dislikes">
			<span class="dislikes-placeholder"><?php echo $dislikes ?></span>
			<span onclick="dislike('<?php echo $article_id ?>')" class="icons">👎</span>
		</div>
	</div>

	<script src="script.js"></script>
</body>
</html>	

Explaining the reactions element

	<div class="reactions">
		<div class="likes">
			<span class="likes-placeholder"><?php echo $likes ?></span>
			<span onclick="like('<?php echo $article_id ?>')" class="icons">👍</span>
		</div>
		
		<div class="dislikes">
			<span class="dislikes-placeholder"><?php echo $dislikes ?></span>
			<span onclick="dislike('<?php echo $article_id ?>')" class="icons">👎</span>
		</div>
	</div>
  • In line 30 we have a div element with a class of "likes". Inside we have two span elements. In the first span element with a class of "likes-placeholder" we echo the $likes variable to display the number of likes that the article has.

    In the second span element in line 32 we display the thumbs-up icon. Also we have an onclick event-listener assigned which triggers a function named like(). The like() function takes as an argument the article's id.

  • In line 35 we have a div element with a class of "dislikes". We have here the same thing as above. In the first span element we display the number of dislikes. And in the second span element we display the thumbs-down icon.

    Again we have an onclick event-listener assigned to the second span element which triggers a function named dislike(), and as we had in the like() function, we have here as well, as an argument, the article's id.

  • This way when we click on the like or dislike icon we will send to the javascript file the article's id. And from there to the php file so we can update the json file.
    It seems fun 😃, so let's move to the javascript file.

The javascript code

In the script.js file we are gonna have two functions. A function named like() which will run when the user clicks on the like icon, and a function named dislike() when the user clicks on the dislike icon.

function like(articleId){
   fetch("script.php?like=" + articleId)
   .then(function(response){
     if(response.status == 200){
        return response.json();
     }
   })
   .then(function(data){
      document.querySelector(".likes-placeholder").innerHTML = data[0];
      document.querySelector(".dislikes-placeholder").innerHTML = data[1];
   });
}

function dislike(articleId){
   fetch("script.php?dislike=" + articleId)
   .then(function(response){
     if(response.status == 200){
        return response.json();
     }
   })
   .then(function(data){
      document.querySelector(".likes-placeholder").innerHTML = data[0];
      document.querySelector(".dislikes-placeholder").innerHTML = data[1];
   });   
}

Explaining the like function

The only thing that the function does is to run an AJAX request to the script.php file.

function like(articleId){
   fetch("script.php?like=" + articleId)
   .then(function(response){
     if(response.status == 200){
        return response.json();
     }
   })
   .then(function(data){
      document.querySelector(".likes-placeholder").innerHTML = data[0];
      document.querySelector(".dislikes-placeholder").innerHTML = data[1];
   });
}
  • The function takes as an argument the article's id and sends it to the script.php file with a GET http request using the fetch method.
  • The php file will send back as a response an array containing the updated likes and dislikes numbers.
  • In line 9 we display the first item data[0] which holds the number of likes in the likes-placeholder, and in line 10 we display the second item from the data array data[1] which holds the number of dislikes in the dislikes-placeholder span element.

Explaining the dislike function

The dislike() function is almost identical with the like() function, except the query string in the GET request which is script.php?dislike=" + articleId. While the query string in the like() function is script.php?like=" + articleId.

function dislike(articleId){
   fetch("script.php?dislike=" + articleId)
   .then(function(response){
     if(response.status == 200){
        return response.json();
     }
   })
   .then(function(data){
      document.querySelector(".likes-placeholder").innerHTML = data[0];
      document.querySelector(".dislikes-placeholder").innerHTML = data[1];
   });   
}

That's all that we have in the javascript file, now let's go to the php file to catch the AJAX request.

The script.php file

In the php file we have basically two sections or two actions if you like. In line 12 we catch the like, and in line 109 we catch the dislike reaction.

Go through the lines of code and read the comments. I don't usually commenting in my tutorials but this is a long piece of code and i felt this style will be more helpful.

<?php 
	// We assume that the user is logged in and we assign his id to the user_id variable.
	$user_id = "36";
	
	// We get the data from the json file.
	$json = file_get_contents("reactions.json");
	
	// Decoding the json data to an array using the keyword true.
	$data = json_decode($json, true);

	// Catching the like key which holds the article's id.
	if(isset($_GET['like'])){
		
		// Assigning the article's id to the $article_id variable.
		$article_id = $_GET['like'];
		
		// Looping through the data array to find the article by its article-id.
		foreach ($data as $key => $value){
		
			// Finding the article that corresponds to the incoming $article_id.
			if($value["article-id"] == $article_id){
				
				// Looping through the users array, to check if the user has already clicked
				// on a like or dislike icon but has changed his mind.
				foreach ($value["users"] as $index => $user) {
					
					// When the user clicks on the like button again to unlike the post.
					if($user["user-id"] == $user_id && $user["reaction"] == "like"){
						
						// Subtract a like and store the number of likes in the $likes variable.
						$likes = -- $data[$key]["likes"]; 

						// getting the number of dislikes.
						$dislikes = $data[$key]["dislikes"]; 
						
						// Using the $index key to remove the users reaction from the 
						// users array.
						unset($data[$key]["users"][$index]);
						
						// Encoding the data back to json.
						$new_data = json_encode($data, JSON_PRETTY_PRINT);
						
						// Put the data back to the file.
						file_put_contents("reactions.json", $new_data);
					
						// returning an array that contains the likes and 
						// dislikes as a response to the javascript file.
						echo json_encode([$likes, $dislikes]);
						exit();
					}

					// When the user clicks on the like button, but he had disliked earlier.
					if($user["user-id"] == $user_id && $user["reaction"] == "dislike"){
						
						// Adding a like and store the number of likes in the $likes variable.
						$likes =  ++ $data[$key]["likes"];

						// Subtracting a like and store the number of dislikes in the
						// $dislikes variable
						$dislikes = -- $data[$key]["dislikes"];
						
						// Updating the users reaction to like.
						$data[$key]["users"][$index]["reaction"] = "like";
						
						// Encoding the data back to json.
						$data = json_encode($data, JSON_PRETTY_PRINT);
						
						// Putting the data back to the json file.
						file_put_contents("reactions.json", $data);	

						// returning an array that contains the likes and 
						// dislikes as a response to the javascript file.
						echo json_encode([$likes, $dislikes]);
						exit();
					}
				} // End of second loop.

				// If the user not exists in the users array.
				// create an array named $user_data with the user-id, and the reaction.
				$user_data = array(
					"user-id" => $user_id,
					"reaction" => "like",
				);

				// Insert the user_data in the users array.
				array_push($data[$key]["users"], $user_data);

				// Increment  the value of likes.
				$likes = ++ $data[$key]["likes"];
				
				// Getting the number of dislikes.
				$dislikes = $data[$key]["dislikes"];
				
				// Encoding the data back to json.
				$new_data = json_encode($data, JSON_PRETTY_PRINT);
			
				// Insert the data back to the file.
				file_put_contents("reactions.json", $new_data);	
				
				// returning an array that contains the likes and 
				// dislikes as a response to the javascript file.  
				echo json_encode([$likes, $dislikes]);
			}
		}
	}

	// Catching the dislike key which holds the article's id.
	if(isset($_GET['dislike'])){
		
		// Assigning the article's id to the $article_id variable.
		$article_id = $_GET['dislike'];

		// Looping through the data array to find the article by its
		// article-id.
		foreach ($data as $key => $value){
		
			// Finding the article that corresponds to the incoming $article_id.
			if($value["article-id"] == $article_id){
				
				// Looping through the users array, to check if the user has already clicked
				// on a like or dislike icon but has changed his mind.
				foreach ($value["users"] as $index => $user) {
					
					// When the user clicks on the dislike button again to un-dislike the post.
					if($user["user-id"] == $user_id && $user["reaction"] == "dislike"){
					
						// Subtract a dislike and store the number of 
						// dislikes in the $dislikes variable.
						$dislikes = -- $data[$key]["dislikes"];
					
						// getting the number of likes.
						$likes = $data[$key]["likes"];

						// Using the $index key to remove the users reaction from the 
						// users array.
						unset($data[$key]["users"][$index]);

						// Encoding the data back to json.
						$data = json_encode($data, JSON_PRETTY_PRINT);
					
						// Put the data back to the file.
						file_put_contents("reactions.json", $data);

						// returning an array that contains the likes and 
						// dislikes as a response to the javascript file.
						echo json_encode([$likes, $dislikes]);
						exit();
					}
					
					// When the user clicks on the dislike button, but he had liked earlier.
					if($user["user-id"] == $user_id && $user["reaction"] == "like"){
					
						// Subtracting a like and store the number of likes in the
						// $likes variable
						$likes =  -- $data[$key]["likes"];
					
						// Adding a dislike and store the number of 
						// dislikes in the $dislikes variable.
						$dislikes = ++ $data[$key]["dislikes"];

						// Updating the users reaction to dislike.
						$data[$key]["users"][$index]["reaction"] = "dislike";

						// Encoding the data back to json.
						$data = json_encode($data, JSON_PRETTY_PRINT);
					
						// Put the data back to the file.
						file_put_contents("reactions.json", $data);	
						
						// returning an array that contains the likes and 
						// dislikes as a response to the javascript file.
						echo json_encode([$likes, $dislikes]);
						exit();
					}
				}
				
				// If the user not exists in the users array.
				// create an array named $user_data with the user-id, and the reaction.
				$user_data = array(
					"user-id" => $user_id,
					"reaction" => "dislike",
				);
				
				// Insert the user_data in the users array.
				array_push($data[$key]["users"], $user_data);
				
				// Increment the value of dislikes.
				$dislikes = ++ $data[$key]["dislikes"];
				
				// getting the number of likes
				$likes = $data[$key]["likes"];

				// Encoding the data back to json.				
				$data = json_encode($data, JSON_PRETTY_PRINT);
				
				// Insert the data back to the file.
				file_put_contents("reactions.json", $data);	
				
				// returning an array that contains the likes and 
				// dislikes as a response to the javascript file.
				echo json_encode([$likes, $dislikes]);
			}
		}
	}

That's all the php code that we need. Now let's run the code and click on the like button.

If we open the reactions.json file we will see that, the object with article-id 001 has one like, and in the users array we have stored the user's id and the reaction which is like.

[
    {
        "article-id": "001",
        "likes": 1,
        "dislikes": 0,
        "users": [
            {
                "user-id": "36",
                "reaction": "like"
            }
        ]
    },
    {
        "article-id": "002",
        "likes": 0,
        "dislikes": 0,
        "users": []
    }
]

Play around with the like and dislike buttons, and check everytime the file to see the changes.

Summary

This is the code that i came up with on how to store likes and dislikes in a json file.
I hope everything is understandable.

Last Words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 73

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal