代码之家  ›  专栏  ›  技术社区  ›  NightPorter

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

  •  0
  • NightPorter  · 技术社区  · 5 年前

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

    我在第一个请求中嵌套了第二个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);
    

    $(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");
          }
        });
    
    });
    

    这把我逼疯了。任何帮助都将不胜感激!

    2 回复  |  直到 5 年前
        1
  •  2
  •   Rohin Prajapati    5 年前

    第二个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");
             }
        });
    
        2
  •  0
  •   kon apaz    5 年前