简体   繁体   中英

How To Make A Like Counter?

I want to make a like counter like Instagram, Facebook etc. What Should I do? I even have a SQLdatabase. I just need the code. SOMEONE PLEASE Help

<html>
<head>
</head>
<body>
<img src="src/to/image" id="image"/>
<button onclick="like()">Like</button>
<script>
function like(){
//What Function Should I Use To Like The Picture
}
</script>
</body>
</html>



You'll need some kind of backend to handle the process of saving a new 'like' into your database. This can be done with PHP for example.

Then, you'll have to make an endpoint which allows to POST some data. This will probably be something like a user ID and an ID for the entity that is 'liked'.

Next, you'll want to use either a simple HTML form or JS fetch() to send this data from your frontend to your backend. This can be implemented in your like() function.

You probably also want to get some data from the backend in order to show the total like count.

Take a look at https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data and https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Complete answer: Well... JavaScript is a client-side script. You will need a server side script. Best example is PHP. If you learn its basics, you can yourself figure out how to do that.

for example, in the main.php file,

<form action="like.php" method = post>
<input type="submit" value="like">
</form>
<?php
$file = fopen("likes.txt","r")
$f = fread($file)
$numOfLikes = strlen(f)
echo "<p> Likes:" .$numOfLikes. "</p>"
?>

in like.php file,

<?php
$f = fopen("likes.txt","w")
fwrite($f, "1")
fclose($f)
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM