如何从数据库中检索 PHP 值并使用 AJAX 在页面上进行更新

我有一个投票功能,它使用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");

      }

    });


});

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


森林海
浏览 115回答 1
1回答

GCT1015

第二个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");         }    });
打开App,查看更多内容
随时随地看视频慕课网APP