【问题标题】:How to retrieve a PHP value from DB and update on page with AJAX如何从数据库中检索 PHP 值并使用 AJAX 在页面上更新
【发布时间】:2020-02-01 11:53:42
【问题描述】:

我有一个投票功能,它使用 AJAX 提交用户投票并更新数据库,而无需刷新页面。到目前为止一切都很好。但我也想从数据库中检索更新的值并在页面上更新它。

我在第一个请求中嵌套了第二个 AJAX 请求。第二个请求调用文件 new_values.php,该文件获取最新值并将它们放入数组中并以 JSON 格式返回,如下所示

     $new_vals = array(
        'new_total' => $new_total,
        'poll_option_1_val' => $poll_option_1_val,
        'poll_option_2_val' => $poll_option_2_val,
     );

    echo json_encode($new_vals);

下面是 Ajax 请求 - 第一个请求可以正常更新数据库,但内部 AJAX 请求不起作用。在下面的示例中,我尝试使用 alert 来显示 new_total 值,但没有任何反应

$(function () { // SUBMIT FORM WITH AJAX

    $('#poll-form').on('submit', function (e) { //on form submit

        e.preventDefault(); // prevent default behaviour

        if($("form")[0].checkValidity()) { // check if the form has been validated

        $.ajax({ // submit process

            type: 'post',
            url: 'vote-process.php',
            data: $('form').serialize(),
            success: function () {

                $('#vote_submitted').modal('show');
                $("input").attr("disabled", "disabled");
                $("textarea").attr("disabled", "disabled");
                $("#vote_button").attr("disabled", "disabled");
                $("#vote_button").text("Vote submitted");

                $.ajax({
                    url : 'new_values.php',
                    type : 'POST',
                    data : data,
                    dataType : 'json',
                    success : function (result) {

                      alert(result['new_total']);

                    },
                    error : function () {
                       alert("error");
                    }
                });
            },

            error: function() { 

                $('#error').modal('show');
            }     
        });
        return false;

      } else { // if the form is not valid

        console.log("invalid form");
      }
    });

});

这让我发疯了。任何帮助将不胜感激!

【问题讨论】:

    标签: php jquery json ajax


    【解决方案1】:

    第二个Ajax数据:数据会给你这个问题需要传递适当的参数

    $.ajax({
             url : 'new_values.php',
             type : 'POST',
             data : {data_return:'yes'},
             dataType : 'json',
             success : function (result) {
                alert(result['new_total']);
             },
             error : function () {
                alert("error");
             }
        });
    

    【讨论】:

    • 成功了!谢谢。如果您不介意,您能否解释一下 {data_return:'yes'} 在做什么?
    • 它的参数变量:你可以在括号中传递任何你想要的记录检索
    【解决方案2】:

    第二个ajax请求中的数据是什么?数据:数据?数据未定义,因此 javascript 可能会停止执行整个代码,尤其是在使用“use strict”时

    【讨论】:

      猜你喜欢
      • 2013-12-04
      • 1970-01-01
      • 2017-07-25
      • 2019-01-21
      • 1970-01-01
      • 2015-09-15
      • 2017-12-05
      • 2020-09-16
      • 2016-02-23
      相关资源
      最近更新 更多