dongshi1606 2017-05-29 08:37
浏览 19
已采纳

将Var从JavaScript传递给php,错误:

I'm triyng to pass a var value from javaScript to php and i'm getting this error Undefined index: postmarca in C: . The objective was to avoid php returning the value of marcaID, which is the primary key and return the selection name defined as "marca", which is obtained from a DB

What am i doing wrong?

<?php

$marca = $_POST['postmarca'];
 echo "$marca";
?>


<html>
<head>
<script type= "text/javascript" src="jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="reg">
    <form>



<select name="marca" class="marca" id="marca">
    <option selected="selected">--Select MArca--</option>
        <?php
          $stmt = $db->prepare("SELECT * FROM tabl_marca");
                     $stmt->execute();
                     while($row=$stmt->fetch(PDO::FETCH_ASSOC))
                                     {
                            ?>
      <option value="<?php echo $row['marcaID']; ?>">
      <?php echo $row['marcas']; ?></option>
    <?php
         } 
     ?>
                        </select>

        <input type="button" value="submit" onclick="post();">
        </form>

</div>
</body>

JAVASCRIPT

<script type= "text/javascript">
    function submit()
    {
    var marca= $('#marca').val();
        $.post('tester.php', {postmarca:marca}, function(data)
        {
            $('#reg').html(data);
        });
    }
    </script>
  • 写回答

2条回答 默认 最新

  • douliao5550 2017-05-29 09:18
    关注

    The variable $_POST['postmarca'] will be set once data is posted from your script to the current script. When you run the script for the first time, 'postmarca' has not been added to the global variable $_POST because the script has not posted the data assuming the current script is tester.php. Try adding a condition to check if the variable is available before using it i.e:

    if(isset($_POST['postmarca'])){
        $marca = $_POST['postmarca'];
        echo $marca;
    }
    

    You might also want to change onclick="post();" to onclick="submit();"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错