douliangli6407 2013-12-16 06:07
浏览 38

AJAX调用成功但在$ _POST ['sample']中抛出未定义的索引错误

I have an AJAX call that passes data to another php file, createTest2.php, as below.

But the createTest2.php file throws error

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; 
?>
  • 写回答

1条回答 默认 最新

  • double0201 2013-12-16 06:11
    关注

    Total stab in the dark here but I'm guessing you have something like this

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

    In which case, you should prevent the default action on the button, eg

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

    What's happening is your form's default method is GET and it is submitting normally, thus $_POST isn't populated.

    Ideally, you should never blindly accept user input. I'd start with some checks in your PHP file

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

    Secondly, catching click events on form submit buttons is rife with problems. For one, there's more than one way to submit a form. You should catch the form's submit event instead, eg

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

    and the JS

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

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示