AJAX和PHP无法通过post方法进行通信

时间:2019-05-01 23:55:30

标签: php ajax

因此,我有一个html表单,其中包含8个问题的测验。我有一个Javascript,可以将分数加起来并给出分数,我想显示它,但也可以通过ajax post方法将分数保存到数据库中到php文件中。现在,我的ajax代码成功执行了一些catch命令,它吐出了我想要的值,但是事实上,我的php代码似乎从未运行过。我没有从我的php代码中获取任何catch错误。

我的javascipt和Ajax:

<script>
document.getElementById("form1").onsubmit=function() {
     q1 = parseInt(document.querySelector('input[name = "q1"]:checked').value);
     q2 = parseInt(document.querySelector('input[name = "q2"]:checked').value);
     q3 = parseInt(document.querySelector('input[name = "q3"]:checked').value);
     q4 = parseInt(document.querySelector('input[name = "q4"]:checked').value);
     q5 = parseInt(document.querySelector('input[name = "q5"]:checked').value);
     q6 = parseInt(document.querySelector('input[name = "q6"]:checked').value);
     q7 = parseInt(document.querySelector('input[name = "q7"]:checked').value);
     q8 = parseInt(document.querySelector('input[name = "q8"]:checked').value);



       result = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8;

    document.getElementById("grade").innerHTML = result;


        $.ajax({
          url: 'quiz1.php',
          type: 'POST',
          data : {result : result},
          success: function (data){

          },
          error: function (data){
            alert("failed to save data");
          }


       });

   }

然后是我的php :(我在其中尝试了一些操作以获得结果,但是甚至没有任何迹象表明php文件的迹象)

<?php

include("phpbook-vars.inc");
$database="yr1005";
$connect=mysqli_connect($hostname,$user,$password);
if(!$connect)
  echo "<h2>Error occurred, failed to connect with MySQL:</h2>".
  mysqli_connect_error()."</b>";
if(!mysqli_select_db($connect, $database))
  echo "Database $database not selected";

  if(isset($_POST['result'])) {
      $score = $_POST['result'];
      echo $score;
  } else {
      echo 'fail';
  }

$query = "INSERT INTO quiz1 (username, quiz1)
VALUES ('anything', '$score)";

if(!mysqli_query($connect, $query)) {
  echo "<h2>Error - couldn't save quiz grade</h2>";
  header ("refresh:3; url=hciQ.html");
} else {
  echo "<h2>Thanks your grade was recorded</h2>";
  header ("refresh:3; url=hciQ.html");
}

 ?>

0 个答案:

没有答案