将执行 PHP 的按钮转换为 jQuery/Ajax

时间:2021-04-10 20:18:12

标签: javascript php jquery

我正在尝试为我的 Fantasy Football League 编写一个功能,允许玩家相互交易。从功能上讲,它一切正常,但由于我已经用 PHP 编写了所有代码,我遇到了一个烦人的问题,即每次按下按钮时,页面都会有效地刷新两次。我已经读到我可以使用 jQuery 和 Ajax 来解决这个问题,但遗憾的是我对这两者都没有任何经验。

以下是一小段代码,允许登录用户撤销他们提出的交易报价:

echo "<input type='submit' id='btn-danger' name='withdraw".$trade_id."' value='Withdraw'>";
    if($_POST && isset($_POST['withdraw'.$trade_id])) {
    $withdraw = $link->prepare("DELETE FROM trade_id_offers_out WHERE trade_id_offer_id = ".$trade_id);
    $withdraw->execute();
    }

这会为他们发出的每笔交易报价创建一个“提款”按钮,并具有唯一名称“提款”加上报价在 SQL 表中的任何数字。

正如我所说的,它在功能上运行良好。但它刷新了页面两次,我想知道如何将这段代码转化为更实用的东西?

非常感谢您抽出宝贵时间。

1 个答案:

答案 0 :(得分:1)

首先,您应该确保在任何其他 jQuery 之前将 jQuery 包含到您的页面 html 中(那里有很多教程)。

其次,您需要为提交按钮指定一个类,以便您可以使用 jQuery 选择器来选择它。把按钮的php代码改成这样:

echo "<input type='submit' id='btn-danger' class='withdrawTradeBtn' name='withdraw".$trade_id."' value='Withdraw'>";

最后,您将向您的网址(在这种情况下与您的页面相同的网址)发出 ajax 发布请求。 js 看起来像这样,需要放置在 html body 标记的末尾之前或在所有按钮都呈现之后:

(注意:我没有测试过这个,但它应该非常接近你所追求的)

<script>
    //we need to wait for the page to be loaded in the users browser
    $(document).ready(function(){
        //we are selecting all the buttons with the class withdrawTradeBtn
        //we are binding to the click event so whenever any of the buttons are pressed the code will be ran.
        $('.withdrawTradeBtn').on('click', function(e){
            //we need to prevent the button from actually reloading the page
            e.preventDefault();
            //now we need to make a ajax post request to the url
            $.post(
                '/your/url', //the url to make the post
                {$(this).attr('name'):'Withdraw'}, //the submitted data 
                function(data, status, jqXHR) {// success callback
                    //here is were you would delete the button or whatever
                }
            );
        });
    });
</script>

您很可能希望从 html 中删除交易条目。您将在 ajax 帖子的成功回调中执行此操作。我真的不能在这里添加任何东西,因为我不知道你的 html 结构是什么样的。

希望这会有所帮助,如果您需要更多帮助,请告诉我!