将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>

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();"

At the first load of the page, you try to get the POST value postmarca, but you did not submit any form.

You should had a condition to see if a form has been submitted, like this:

if (!empty($_POST['postmarca'])) {
    echo $_POST['postmarca'];
}

I am assuming that the file you posted is called tester.php.

In that case, you may have an issue, because the $.post made in Javascript is an AJAX call, and it will include all your tester.php file, and you will have kind of a code inception here.

You can put the code I wrote in a new file, called per example submit.php, and then you avoid the code inception.