dousuo8400 2014-08-30 11:50
浏览 78
已采纳

jquery ajax请求中的未定义索引错误

Please check my code in the following:

PHP & HTML Code(file1.php):

<?php
$conn = //connected to db successfully.
$sql = "SELECT t1.column1 AS Column_1 FROM table1 t1";
$rs = mysqli_query($conn,$sql);
$rows= mysqli_fetch_assoc($rs);
do{
?>
<button data-id="<?php echo $rows['Column_1']; ?>" type="button" onclick="handle_item('id')">Click Me</button> <br>
<?php }while($rows = mysqli_fetch_assoc($rs)); ?>

jQuery AJAX code(file1.php):

<script type="text/javascript">
    var item_id;
    function handle_item(item_id) {
        var c = $(this).data(item_id);
        $.ajax({
            url: 'handle_input.php',
            type: 'POST',
            data: {
                'button_id': c
            },
            success: function (data) {
                alert(data);
            }
        });
    }
</script>

PHP Code(handle_input.php):

<?php
echo "Button with id ".$_POST['item_id]." clicked!";
?>

Now the problems is (as you might expect) the infamous error in this case, "undefined index: button_id" error. I receive it as an alert error when I click on one of the buttons. I've already read the duplicate questions on SO but unfortunately none of those I read could resolve my problem. I appreciate your guiding me with this.

Besides, as you see from my codes, I'm fetching several button from database and while displaying, I assign each one a data-id and use that data-id in ajax to use in 'handle_input.php' and I want to receive each button id which I've clicked on. Thanks in advance.

UPDATE:

It's been a while since I've asked this question but I've been curios about something in my question: Why doesn't the array mode(data: {"button_id":c}) work for me in the $.ajax function(which leads to undefined index error for the $_POST variable) whereas the string mode(data: "usg_id="+c) does?

  • 写回答

2条回答 默认 最新

  • drj26159 2014-08-30 12:01
    关注

    You're sending:

    button_id:..
    

    but you're using, also with a missing '

    $_POST['item_id]
    

    change to:

    $_POST["button_id"]
    

    UPDATE

    Add this as first parameter:

    onclick="handle_item(this, 'id')"
    

    Then, changehandle_item function as this:

    function handle_item(obj,item_id) {
        var c = $(obj).data(item_id);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置