简体   繁体   English

PHP、AJAX、HTML:可以在不刷新页面的情况下更新数据库的点赞按钮

[英]PHP, AJAX, HTML: Like button that can update database without refreshing page

I've got a like button, which holds an ID from a database.我有一个点赞按钮,它包含来自数据库的 ID。 I'm trying click the like button, update a database and then it'll switch to unlike without reloading the page.我正在尝试单击“喜欢”按钮,更新数据库,然后它会在不重新加载页面的情况下切换到“不像”。

I'll paste the code below, so you have an understanding:我将粘贴下面的代码,以便您有所了解:

**index.php: ** **索引.php:**

<script type="text/javascript">

// Like Button Function
    $(document).ready(function(){ 
        $(".likeBtn").on("click", function(){
        
        var threadID = $(this).attr("id");
        console.log(threadID);

        $.ajax({
             type: "POST",
             url: "like_function.php",
             data: threadID,
             success:function(html)
             {
             }
        });

        });
    });

</script>
<form action='javascript:void(0);' method='POST' enctype='multipart/form-data'>
   <input type='submit' name='likeBtn' class='likeBtn' id='52' value='Like'>
</form>

So the var threadID = retrieving an ID from database (I used 52 as example) From here, I want to be able to run a php script (like_function.php) to update database using the ID stored as a variable.所以 var threadID = 从数据库中检索 ID(我使用 52 作为示例)从这里,我希望能够运行一个 php 脚本(like_function.php)来使用存储为变量的 ID 更新数据库。

Lastly, I want that button to change to unlike.最后,我希望该按钮更改为 unlike。 Sorry for being a noob at this.对不起,我是个菜鸟。 I'm new to Ajax我是 Ajax 新手

You need to use a preventDefault() to cancel the event submit and now you can update your data.您需要使用preventDefault()取消事件submit ,现在您可以更新数据。 Example below:下面的例子:

$(document).ready(function(){ 
        $(".likeBtn").on("click", function(e){ // set e in arguments
        
        e.preventDefault(); // use this
        var threadID = $(this).attr("id"); // [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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