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 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大