获取从AJAX传递的值时,php中未定义的索引

时间:2016-05-02 02:39:18

标签: javascript php jquery ajax

我试图将我在AJAX中传递的值传递给PHP。它显示了一个警告,说“成功!"但是当我尝试在PHP中显示值时,它表示未定义的索引。我也在同一页面传递它。

每当我点击一个按钮时,它会打开一个模态,我也会将该按钮的值传递给模态。这在我的JS代码中很明显。

<script>
        $(document).ready(function(){
          $('#editModal').on('show.bs.modal', function (e) {

            var id = $(e.relatedTarget).data('id'); //im trying to pass this value to php, e.g. 5
            var time = $(e.relatedTarget).data('time');
            var name = $(e.relatedTarget).data('name');
            var stat = $(e.relatedTarget).data('stat');
            var desc = $(e.relatedTarget).data('desc');
            alert(id);
            $("#task_id_edit").val(id);
            $("#new-taskID").val(id);

            $("#allotted_time_edit").val(time);
            $("#task_name_edit").val(name);
            $("#task_status_edit").val(stat);
            $("#task_desc_edit").val(desc);
            $("#task_id_ref2").val(id);


           //AJAX CODE HERE
           $(function() {
                $.ajax({
                    type: "POST",
                    url: 'tasks.php?id='<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>,
                    data: { "userID" : id },
                    success: function(data)
                    {
                        alert("success!"); //this display
                    }
                });
           });



           }); // line 1131
        });
</script>

PHP代码:

<?php

   $uid = $_POST['userID'];
   echo $uid." is the value"; 

?>

它不断收到错误,指出未定义的索引:userID。我很迷惑。请帮我解决这个问题。非常感谢您的帮助!谢谢!

2 个答案:

答案 0 :(得分:2)

回显javascript字符串中的数字。

目前您将获得:

  

URL:&#39; tasks.php ID =&#39; 1,

1应该连接在引号内。尝试:

url: 'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',

或取出该参数,因为它似乎没有被使用。

答案 1 :(得分:-2)

只需将$_POST['userID']放入if语句

即可

未定义的索引:UserID不是错误,它是一个警告

<?php
   if(isset($_POST['userID'])
   {
   $uid = $_POST['userID'];
   echo $uid." is the value"; 
   }
   else
   {
     echo "Sorry Value cant be printed";
   }

?>