-1

I'm using post method to get the id but everytime tells me Undefined variable $id here is my code:

<?php    
    require 'DBConnection.php';
    $code='';
    if(isset($_POST["ID"])){
        if($_POST(["ID"]) != ''){
            $id = $_POST['ID'];
            $get_c = $pdo->prepare("SELECT * FROM all_menu WHERE `ID` = '".$id."'");
            $get_c->execute(); 
            while ($row = $get_c->fetch()) {
                $code .= $row['item_code'];
            }
            echo $code;
        }
    }

Edit: I'm using this code to select from dropdown options to get the ID of the value in dropdown for example I have three options in my select dropdown let's say the first one is "Pepsi" when I select "Pepsi" I need to put its ID in an input I'm using PHP and Ajax in this code.

Here is my Ajax code:

<script>
  $(document).ready(function(){
    $('#itemname').change(function(){
      var code = $(this).val();  
       $.ajax({
          type: 'POST',
          url: 'pages/GetCode.php',
          data:{code:code},
          success: function(data){
            document.getElementById("itemcode").value = data;
          },
          error: function (jqXHR, textStatus, errorThrown){ 
            alert(errorThrown);
          }
       });
    });
  });
</script>

2 Answers2

1

If you are calling this php page from the javascript AJAX, then I can see the only parameter is "code", so how can you expect "ID" in the POST?

Either change the javascript, or the PHP file.

The below javascript will send "code" as POST parameter, data:{"code":code},

<script>
  $(document).ready(function(){
    $('#itemname').change(function(){
      var code = $(this).val();  
       $.ajax({
          type: 'POST',
          url: 'pages/GetCode.php',
          data:{"code":code},
          success: function(data){
            document.getElementById("itemcode").value = data;
          },
          error: function (jqXHR, textStatus, errorThrown){ 
            alert(errorThrown);
          }
       });
    });
  });
</script>

Use "code" instead of "ID" as POST parameter in PHP

<?php    
    require 'DBConnection.php';
    $code='';
    if(isset($_POST["code"])){
       if($_POST(["code"]) != ''){
            $id = $_POST['code'];

Side Note: Do not use user input (here "code") in the SQL query, that way your sql query will be open to injection.

Subhashis Pandey
  • 1,473
  • 1
  • 13
  • 16
1

You are sending param code as ajax data and you are fetching param id Change $_POST['id'] to $_POST['code']

$id = $_POST['code'];

Sho
  • 175
  • 3
  • 17