简体   繁体   English

jQuery和AJAX单击仅可使用一次

[英]jQuery and AJAX on click only works once

I am trying to make a like/unlike button with jQuery and Ajax. 我正在尝试使用jQuery和Ajax创建一个喜欢/不喜欢的按钮。 Problem is that when I like something I can't unlike it until I refresh the page, and if I unlike something, I can't like it again until I refresh the page. 问题是,当我喜欢某件事时,直到刷新页面后才喜欢它;如果我不喜欢某事,则直到刷新页面后,我才能再次喜欢它。

Here's my PHP/html: 这是我的PHP / html:

<?php
require('con.php');
session_start();

if (!empty($_POST)) {
    $un = $_SESSION['un'];
    $op = $_POST['op'];
    $pid = $_POST['pid'];
    if ($op == "like") {
        mysqli_query($con, "INSERT INTO likes (pid, uid, date_liked, username) VALUES ('$pid', '".$_SESSION['id']."', now(), '".$_SESSION['un']."')") or die(mysqli_error($con));
        echo 1;
        exit;
    } elseif ($op == "unlike") {
        mysqli_query($con, "DELETE FROM likes WHERE pid = '$pid' AND username = '$un'");
        echo 1;
        exit();
    }
}    
?>
<!DOCTYPE html>
<html>
<head>
    <title>Test 2 Test</title>
    <script src="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<?
$sql = mysqli_query($con, "SELECT * FROM posts") or die(mysqli_error($con));
//get all the posts from the posts table
while ($r = mysqli_fetch_assoc($sql)) {
    $b = $r['body'];
    $u = $r['uid'];
    $pid = $r['pid'];

    $s = mysqli_query($con,"SELECT username, pid FROM likes WHERE pid = '$pid' ") or die(mysqli_error($con));
    //get all the likes that correspond with the post id from the likes table
    $n = mysqli_num_rows($s);
    //the number of likes
    $r = mysqli_fetch_assoc($s);
    $user = $r['username'];
    if ($user !== $_SESSION['un']) {
    //if the user hasn't liked the post yet
        echo "<div>$b</div>";
        echo "<input type = 'button' value = '$n' id = 'like_$pid' class='$pid'>";
        //the like button
        echo "<br><br>"; ?>
        <!-- jQuery Script here -->

    <?
    } else {
    //the user has liked the post
        echo "<div>$b</div>";
        echo "<input type = 'button' value = '$n' id = 'unlike_$pid' class='$pid'>";
        //the unlike button
        echo "<br><br>"; ?>
        <!-- More jQuery -->
   <? 
    }
}
?>

My jQuery: 我的jQuery:

$(document).ready(function() {
    $('#like_' + <? echo $pid; ?>).click(function() {
        var val = parseInt($(this).val(), 10);
        var pid = $("." + <? echo $pid; ?>).val();
        //create a variable with the num of likes
        $.post("test2test.php", {op: "like", pid: pid}, function(data) {
            val = val + 1;
            $('#like_' + <? echo $pid; ?>).val(val);
            $("#like_" + <? echo $pid; ?>).attr("id", "unlike_<? echo $pid; ?>");
        });
     });
     $('#unlike_' + <? echo $pid; ?>).click(function() {
        var val = parseInt($(this).val(), 10);
        var pid = $("." + <? echo $pid; ?>).val();
        $.post("test2test.php", {op: "unlike", pid: pid}, function(data) {
            val = val - 1;
            $("#unlike_" + <? echo $pid; ?>).val(val);
            $('#unlike_' + <? echo $pid; ?>).attr("id", "like_<? echo $pid; ?>");
        });
    });
});

I put this code wherever it said <!--jQuery Script here--> or <!--More jQuery--> 我将这段代码放在<!--jQuery Script here--><!--More jQuery-->

All of this is on one page. 所有这些都在一页上。 I'm not getting any PHP of javascript errors, so I don't know what's up. 我没有收到任何PHP的JavaScript错误,所以我不知道怎么回事。

Please help me. 请帮我。

PS: I am a beginner in jQuery so please don't make your answer too complicated. PS:我是jQuery的初学者,所以请不要使您的答案过于复杂。

Thank you. 谢谢。

问题是您的ID更改仅能做到这一点:它会更改ID,但是ID的事件处理程序不会自动分配给它

Your event doesnt get attached to the elements that are added dynamically after the page load. 您的事件不会附加到页面加载后动态添加的元素上。 Try event delegation. 尝试事件委托。 Also, since you are changing the id of the button each time, you can use wildcard selector as shown below Use 另外,由于每次都更改按钮的ID,因此可以使用通配符选择器,如下所示:

$('body').on('click', '[id^=unlike]', function(){ // or [id^=like]
//your logic
});

instead of 代替

$('#unlike_' + <? echo $pid; ?>).click(function() {
});

and similarly change it for like too. 并同样进行更改。

Instead of modifying the element's ID, modify another attribute, such as a class and that way you don't need to re-apply the click event handler and you can use one single event handler to handle ALL the like/unlike buttons instead of looping over them, which looks like what you are doing. 无需修改元素的ID,而是修改另一个属性(如类),这样就无需重新应用click事件处理程序,并且可以使用一个事件处理程序来处理所有类似按钮/不一样按钮,而无需循环越过它们,看起来就像您在做什么。 And instead of putting a unique number in the ID, you could use the data attribute so that you don't need to worry about extracting the integer from the string (since IDs can't start with integers). 而且,您可以使用data属性,而不用在ID中添加唯一的数字,这样就不必担心从字符串中提取整数(因为ID不能以整数开头)。 In fact, you can completely leave the PHP out of your JavaScript. 实际上,您可以完全将PHP排除在JavaScript之外。

So for example, if you have the following HTML: 因此,例如,如果您具有以下HTML:

<div data-id="12345" class="clickme like"></div>
<div data-id="23456" class="clickme unlike"></div>

Where "like" is for a button to like it and "unlike" is for an unlike button. “喜欢”是按钮喜欢的地方,“喜欢”是不喜欢按钮的地方。 Then you could do the following: 然后,您可以执行以下操作:

$(document).ready(function() {
    $('.clickme').click(function() {
        // Like it:
        if ($(this).hasClass("like")) {
            var pid = $(this)attr("data-id");
            $.post("test2test.php", {op: "like", pid: pid});
            $(this).removeClass("like");
            $(this).addClass("unlike");
        }
        // Unlike it:
        else {
            var pid = $(this)attr("data-id");
            $.post("test2test.php", {op: "unlike", pid: pid});
            $(this).addClass("like");
            $(this).removeClass("unlike");
        }
    });
});

Also, even though this isn't directly related to your question. 此外,即使这与您的问题没有直接关系。 It is always a good habit to use prepared statements with parameterized queries mysqli, even if the values come from the database or a source you consider to be trustworthy. 即使参数值来自数据库或您认为值得信赖的来源,也要始终使用带有参数化查询mysqli的预处理语句,这是一个好习惯。 For example, your $pid variable goes straight into your query opening you up to SQL injection attacks. 例如,您的$pid变量直接进入查询,使您容易受到SQL注入攻击。 Just prepare with parameterized queries and don't worry about what goes into your database. 只需准备参数化查询,就不必担心数据库中包含什么内容。

The button id is changed so the event cannot be triggered. 按钮ID已更改,因此无法触发事件。 You may use the jQuery ".on()" function instead of ".click()", the event will be trigger even the element is created in the future. 您可以使用jQuery“ .on()”函数而不是“ .click()”,即使将来创建该元素,也会触发该事件。

For example, 例如,

$('#like_' + pid).on("click",function(){
   alert("The button is clicked");
});

Reference : https://api.jquery.com/on/ 参考: https : //api.jquery.com/on/

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

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