提交后ajax不会刷新表单,但会发布数据

时间:2018-12-10 20:36:31

标签: php jquery ajax

这是我为表决系统编写的代码。这是我主要网站以外的测试。我是ajax和jquery的新手,无法理解为什么提交表单后我没有重新提交表单。 它仍然发布数据,如果我要刷新页面,它将显示新结果。从我发现的内容来看,这与ajaz部分有关,但对ajax和jquery来说是新的

    enter code here


  <!doctype html>
<html>  
    <head>  
        <title>Live Poll System in PHP Mysql using Ajax</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">  
            <br />  
            <br />
   <br />
   <h2 align="center">Live Poll System in PHP Mysql using Ajax</h2><br />
   <div class="row">
    <div class="col-md-6">
     <form method="POST" id="poll_form">
      <h3>Which is Best PHP Framework in 2018?</h3>
      <br />
      <div class="radio">
       <label><h4><input type="radio" name="poll_option" class="poll_option" value="Laravel" /> Laravel</h4></label>
      </div>
      <div class="radio">
       <label><h4><input type="radio" name="poll_option" class="poll_option" value="CodeIgniter" /> CodeIgniter</h4></label>
      </div>
      <div class="radio">
       <label><h4><input type="radio" name="poll_option" class="poll_option" value="CakePHP" /> CakePHP</h4></label>
      </div>
      <div class="radio">
       <label><h4><input type="radio" name="poll_option" class="poll_option" value="Symfony" /> Symfony</h4></label>
      </div>
      <div class="radio">
       <label><h4><input type="radio" name="poll_option" class="poll_option" value="Phalcon" /> Phalcon</h4></label>
      </div>
      <br />
      <input type="submit" name="poll_button" id="poll_button" class="btn btn-primary" />
     </form>
     <br />
    </div>
    <div class="col-md-6">
     <br />
     <br />
     <br />
     <h4>Live Poll Result</h4><br />
     <div id="poll_result">
     </div>
    </div>
   </div>


   <br />
   <br />
   <br />
  </div>
</body>
</html>
<script>  
$(document).ready(function(){

 fetch_poll_data();

 function fetch_poll_data()
 {
  $.ajax({
   url:"fetch_poll_data.php",
   method:"POST",
   success:function(data)
   {
    $('#poll_result').html(data);
   }
  })  
 };

});    
$(document).ready(function(){


 $('#poll_form').on('submit', function(event){
  event.preventDefault();
  var poll_option = '';
  $('.poll_option').each(function(){
   if($(this).prop("checked"))
   {
    poll_option = $(this).val();
   }
  });
  if(poll_option != '')
  {
   $('#poll_button').attr("disabled", "disabled");
   var form_data = $(this).serialize();
   $.ajax({
    url:"poll.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     $('#poll_form')[0].reset();
     $('#poll_button').attr('disabled', false);
     fetch_poll_data();
     alert("Poll Submitted Successfully");
    }
   });
  }
  else
  {
   alert("Please Select Option");
  }
 });

});  
</script>

这是poll.php

<?php

include("database_connection.php");

if(isset($_POST["poll_option"]))
{

 $query = "
 INSERT INTO tbl_poll 
 (php_framework) VALUES (:php_framework)";
 $data = array(
  ':php_framework'  => $_POST["poll_option"]
 );
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

?>

这就是我要获取的数据。

<?php

//fetch_poll_data.php

$connect = new PDO("mysql:host=localhost;dbname=commentsection","root","");

$php_framework = array("Laravel", "CodeIgniter", "CakePHP", "Phalcon", "Symfony");

$total_poll_row = get_total_rows($connect);

$output = '';
if($total_poll_row > 0)
{
 foreach($php_framework as $row)
 {
  $query = "
  SELECT * FROM tbl_poll WHERE php_framework = '".$row."'
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $total_row = $statement->rowCount();

  $percentage_vote = round(($total_row/$total_poll_row)*100);
  $progress_bar_class = '';
  if($percentage_vote >= 40)
  {
   $progress_bar_class = 'progress-bar-success';
  }
  else if($percentage_vote >= 25 && $percentage_vote < 40)
  {
   $progress_bar_class = 'progress-bar-info';
  }
  else if($percentage_vote >= 10 && $percentage_vote < 25)
  {
   $progress_bar_class = 'progress-bar-warning';
  }
  else
  {
   $progress_bar_class = 'progress-bar-danger';
  }  
     $output .= '
   <div class="row">
    <div class="col-sm-2" align="right">
     <label>'.$row.'</label>
    </div>
    <div class="col-sm-10">
     <div class="progress">
      <div class="progress-bar '.$progress_bar_class.'" role="progressbar" aria-valuenow="'.$percentage_vote.'" aria-valuemin="0" aria-valuemax="100" style="width:'.$percentage_vote.'%">
       '.$percentage_vote.' % programmer like <b>'.$row.'</b> PHP Framework
      </div>
     </div>
    </div>
   </div>
  ';
 }
}

echo $output;


function get_total_rows($connect)
{
 $query = "SELECT * FROM tbl_poll";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

?>

最后,这就是我用于数据库连接的东西。

<?PHP

$connect = new PDO("mysql:host=localhost;dbname=commentsection","root","");

?>

2 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您希望页面在提交表单时重新提交吗?在这种情况下,您需要删除:

event.preventDefault(); 从: $('#poll_form').on('submit', function(event){}

event.preventDefault();取消了提交按钮的默认操作,这就是为什么没有重新提交的原因。

答案 1 :(得分:0)

答案-TLDR-在第一个文档就绪函数中声明的fetch_poll_data不能在第二个文档就绪函数中使用。

(索引):115未捕获的参考错误:未定义fetch_poll_data

您要在第一个$(document).ready(function () { ... });中声明fetch_poll_data()函数,然后尝试在第二个$(document).ready(function () { ... });中重用它。

使用JQuery,您只需要 1 文档准备功能。

使用您的代码固定:

<script>
    function fetch_poll_data() {
        $.ajax({
            url: "fetch_poll_data.php",
            method: "POST",
            success: function (data) {
                $('#poll_result').html(data);
            }
        })
    };

    $(document).ready(function () {

        fetch_poll_data();

        $('#poll_form').on('submit', function (event) {
            event.preventDefault();
            var poll_option = '';
            $('.poll_option').each(function () {
                if ($(this).prop("checked")) {
                    poll_option = $(this).val();
                }
            });
            if (poll_option != '') {
                $('#poll_button').attr("disabled", "disabled");
                var form_data = $(this).serialize();
                $.ajax({
                    url: "poll.php",
                    method: "POST",
                    data: form_data,
                    success: function (data) {
                        $('#poll_form')[0].reset();
                        $('#poll_button').attr('disabled', false);
                        fetch_poll_data();
                        alert("Poll Submitted Successfully");
                    }
                });
            } else {
                alert("Please Select Option");
            }
        });

    });
</script>

最佳做法推荐

我强烈建议更改您使用JQuery和Ajax的方式。我也是从PHP开发者开始的,比仅通过javascript数据发送HTML发送到浏览器要容易得多。但是,随着浏览器变得越来越快,并且数据流需求越来越多,我建议仅以JSON形式返回数据,并让客户端呈现HTML,在网络方面它也变得更小,更快。

SQL-您是否正确存储数据?

当前,我相信您正在将每个框架的新行添加到名为tbl_poll的表中。这可能变得非常大。假设您每个框架每天有1000票,也就是说5000 x 24 x 30 =每月360万条记录

宁可将民意调查存储为整数,然后每计数加1。您正在使用PDO,然后可以按照UPDATE Polls SET Votes = Vote + 1 WHERE Framework = "Example Framework"

行执行SQL

在成功返回数据时更新进度条:

仅发送号码后。然后,您可以使用以下Javascript / JQuery更新Bootstrap进度栏。它将更新引导进度条的值和动画:

            let dataFromPhp = [
            {
                name: "exampleFramework1",
                votes: '5'
            },
            {
                name: "exampleFramework2",
                votes: '45'
            },
            {
                name: "exampleFramework3",
                votes: '21'
            }
        ]

$.ajax({
        url: "fetch_poll_data.php",
        method: "GET",
        dataType: 'json',
        contentType: 'application/json',
        success: function (dataFromPhp) {
            $.each(dataFromPhp, function (eachObject) {
                $('#progress-bar-id-' + eachObject.name).css('width', eachObject.votes + '%').attr('aria-valuenow', eachObject.votes);
            });
        }
    });