AJAX调用成功,但在$_POST中引发未定义索引错误[';sample';]


AJAX call success but throws Undefined index error in $_POST['sample']

我有一个AJAX调用,它将数据传递到另一个php文件createTest2.php,如下所示。

但是createTest2.php文件抛出错误

Notice: Undefined index: sample in C:'xampp'htdocs'TestProj'Test'createTest2.php on line 2

caller.php

 $(document).ready(function(){
 $("#button_submit").click(function() 
 {
  $.ajax({
  type:"POST",
  url:"createTest2.php",
  data:{sample : "test"},
  success:function()
  {
    alert("success");
  }
});
});
});

createTest2.php

  <?php
       $test_name = $_POST['sample'];
       echo $test_name; 
?>

这里完全是暗箱操作,但我猜你有这样的

<form action="createTest2.php">
    <!-- some elements here -->
    <input type="submit" id="button_submit">
</form>

在这种情况下,您应该阻止按钮上的默认操作,例如

$("#button_submit").on('click', function(e) {
    e.preventDefault();
    // and the rest of your ajax code
});

发生的情况是,表单的默认方法是GET,并且它是正常提交的,因此$_POST没有被填充。

理想情况下,您永远不应该盲目地接受用户输入。我会从你的PHP文件中的一些检查开始

if (!isset($_POST['sample'])) {
    http_response_code(406);
    throw new Exception('sample data not submitted via POST');
}
$test_name = $_POST['sample'];

其次,在表单提交按钮上捕捉点击事件充满了问题。首先,提交表格的方式不止一种。你应该抓住表格的提交事件,例如

<form id="myForm" action="createTest2.php">
    <!-- etc -->
    <button type="submit">Go</button>
</form>

和JS

$('#myForm').on('submit', function(e) {
    e.preventDefault();
    $.post(this.action, { sample: 'test' }).done(function(data) {
        alert('Success');
    });
});