简体   繁体   English

在ajax调用后,php函数的按钮不起作用

[英]Button for php function doesnt work after ajax call

I am attempting to add, or subtract a pts field in a database based on if you press a button and then update the content on the page, I also have the fields that the pts are being display in , on a timer with Ajax to auto-refresh. 我尝试根据是否按下按钮然后更新页面上的内容来添加或减去数据库中的pts字段,我也拥有pts所显示的字段,在带有Ajax的计时器上自动-刷新。

I am using this script to call the page: 我正在使用此脚本来调用页面:

$(document).ready(function(){
        var timer, delay = 1000;                // 1 second(s) counted in milliseconds
        var Pts = '';                          //ID value of users answer
        var info = {'userPts': Pts};           //naming POST for php
        timer = setInterval(function(){
            $.ajax({
                url: "inc/ans.php",            //sends to ans page where php function updates DB
                type: "POST",
                data : info,                   //stuff being sent to php
                success:function(data)
                {
                    $("div #ans").html(data);  //Retrieves answers made by user
                }
            });
        }, delay);

My issue is when I make this call the only way currently to click the buttons is to manually refresh the entire page and then I am able to click the buttons and update the users pts value. 我的问题是,当我进行此调用时,当前唯一单击按钮的方法是手动刷新整个页面,然后能够单击按钮并更新用户的pts值。 I am able to do one or the other but not at the same time, I can have it where it auto-refreshes the content but I can't have the button press complete the action. 我可以做一个或另一个,但不能同时进行,我可以在自动刷新内容的地方使用它,但是不能按下按钮来完成操作。 And I can have the buttons be able to be pressed but I can't have the content auto-refresh. 而且我可以使按钮可以被按下,但是内容不能自动刷新。

The PHP functions to add and subtract are about the same they are like this: PHP函数的加法和减法大致相同,如下所示:

    function addPoint($mysqli, $id)
    {
        $stmt = $mysqli->prepare('
        UPDATE tbl_user 
        SET user_pts = user_pts + 1
        WHERE user_id = ?');
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $rows = $stmt->affected_rows; 
        $stmt->close();
        if($rows == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Only difference between the two functions is the fact that its -1 or +1. 这两个函数之间唯一的区别是它的-1或+1。 Any ideas on why this happens? 关于发生这种情况的任何想法? Is it the Ajax call this is interfering with the PHP function or vic. Ajax调用,它干扰了PHP函数或vic。 versa? 反之亦然?

EDIT: This is the code that is being displayed to the instructor with the buttons 编辑:这是通过按钮显示给教师的代码

    function getScore_I($mysqli)
    {
        $stmt = $mysqli->prepare('
        SELECT user_name, user_pts, user_id
        FROM tbl_user');
        $stmt->execute();
        $stmt->bind_result($user, $pts, $id);
        $O ="";
        $x = 1;
        $O.="<table style=\"text-align:center;width: 100%\"><form action=".$_SERVER['PHP_SELF']." method=\"POST\">";
        while($stmt->fetch())
        {
            if($x%2)
            {
                $O.= "<tr style=\"text-align:center;width: 100%\">
                        <td>".$user."</td>
                        <td>
                            <button name=\"userIDmiunus\" type=\"submit\" value=\"".$id."\">-</button>
                        </td>
                        <td>".$pts."</td>

                        <td>
                            <button name=\"userIDplus\" type=\"submit\" value=\"".$id."\">+</button>
                        </td>
                    </tr>";
                $x++;
            }
            else
            {
                $O.= "<tr style=\"text-align:center;width: 100%\">
                        <td>".$user."</td>
                        <td>
                            <button name=\"userIDmiunus\" type=\"submit\" value=\"".$id."\">-</button>
                        </td>
                        <td>".$pts."</td>

                        <td>
                            <button name=\"userIDplus\" type=\"submit\" value=\"".$id."\">+</button>
                        </td>
                    </tr>";
                $x++;
            }
        }
        $O.= "</form></table>";
        // close statement
        $stmt->close();
        return $O;
    }

Is it the case that the button elements are included in the code brought in via AJAX? 在通过AJAX引入的代码中是否包含按钮元素? If so, you need to use .on() , as in: 如果是这样,则需要使用.on() ,如下所示:

$(document).on('click', '.buttonClassName', function(){
    //do your click code here
});

Reviewing your code, it looks like you are just doing a .load() , which is a shortcut version of $.ajax() . 查看您的代码,看来您只是在执行.load() ,这是$.ajax()的快捷方式。 I also prefer using $.ajax() in all circumstances - use $.load() , $.get() and $.post() are not as well structured as the full $.ajax() 我也更喜欢在所有情况下都使用$.ajax() -使用$.load()$.get()$.post()的结构不如完整的$.ajax()

When the new data is injected into the DOM via .html() , any controls are not bound to javascript code, since the binding code was run prior to their injection. 当通过.html()将新数据注入DOM时,任何控件都不会绑定到javascript代码,因为绑定代码是在注入之前运行的。 Two solutions: you can also inject some additional javascript and recreate those bindings -- which means much duplicate code in the DOM -- or you can use .on() which works for the elements currently in the DOM, but also for all future elements injected into the DOM that have that specific class or ID or whatever jQuery selector you use. 两种解决方案:您还可以注入一些其他的javascript并重新创建这些绑定-这意味着DOM中有很多重复的代码-或可以使用.on()来处理DOM中当前的元素,也可以使用所有将来的元素注入到具有该特定类或ID或您使用的任何jQuery选择器的DOM中

Another possibility could be that you need to use AJAX to access your PHP function. 另一种可能是您需要使用AJAX来访问PHP函数。 See this post and the post it references/links to regarding AJAX. 请参阅此帖子 以及它引用/链接到的有关AJAX 的帖子 Check out the examples. 查看示例。


Yes, you can call another AJAX function inside the .on(), and that is probably what you need to do. 是的,您可以在.on(),内调用另一个AJAX函数.on(),这可能就是您需要做的。

Recall that AJAX is just a method for running PHP code after the web page has been rendered, and without refreshing/leaving the current page. 回想一下,AJAX只是在呈现网页运行PHP代码的一种方法,而无需刷新/离开当前页面。

Code could look something like this: 代码可能看起来像这样:

$(document).on('click','.buttonClass', function(){
    var Pts = '';                          //ID value of users answer
    var uid = $('hidden_input_where_you_stored_userID').val();
    var info = {'userID': uid, 'userPts': Pts};           //naming POST for php
    $.ajax({
        url: "inc/another_file.php",
        type: "POST",
        data : info,
        success: function(data) {
            //whatever you need to do after updating point score
        }
    });
});

another_file.php: another_file.php:

<?php
    $id =  $_POST['userID'];
    $pts = $_POST['userPts']; 
    //do your DB update

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

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